0

I'm working on the Admin view in Yii for my Project model.

One of the columns with a filter is user (owner) of the project.

I can do something like this:

'filter'=> CHtml::dropDownList('Project[user_id]', $model->user_id,
    CHtml::listData(User::model()->orderAsc()->findAll(),
    'id','username'),array('empty'=>'(select)')),

Which gives me a list of all users in the user table, but I'd like to create something that pulls the distinct users who own a project (I've got 200 users, but only a handful tend to create projects).

Project and User are related via:

'user' => array(self::BELONGS_TO, 'User', 'user_id')

I've tried a bunch of option in the findAll() method, but none worked, I'm not trying to do something with a scope.

So far I've tried this:

'filter'=> CHtml::dropDownList('Project[user_id]', $model->user_id,
    CHtml::listData(Project::model()->with('user')->ownerUsernames()->
    findAll(), 'id','username'),array('empty'=>'(select)')),

and my Scope is defined as:

'ownerUsernames' => array(
    'with' => 'user.username',
    'select' => 'user.username',
    'distinct' => true,
),

I've tried so many iterations of the above I've lost count 'with'=>'username' 'select'=>'username' etc., but just can't seem to get it to work.

I've tried replace Project::model() with $model just because I thought it might have something to do with it, but no luck.

Any ideas are appreciated. Very new to Yii, but this seems like something it can do.

4

2 回答 2

1

你已经准备好了一切。为项目模型定义一个 getter 函数,如

public function getUsername()
{
return $this->user->name;
}

现在你应该可以使用

CHtml::dropDownList('Project[user_id]', $model->user_id,
    CHtml::listData(Project::model()->with('user')->ownerUsernames()->
    findAll(), 'id','username'),array('empty'=>'(select)'))

逻辑是 CHtml::listData 将项目作为模型获取,它将使用 $project->id 创建键,并将使用 $project->username 创建值。因为您创建了 getted 函数,所以它会知道 $project->username 是什么。不幸的是 CHtml::listData(Project::model()->with('user')->ownerUsernames()->findAll(), 'id','user.name') 将不起作用,因为它无法执行 'user .name' 或类似的东西。

于 2014-03-01T02:32:53.630 回答
0

实际上,您可以做很多事情来实现这一点,但是由于时间消耗,有些方法不合适。我更喜欢解决这个问题

  1. 在名为 user_project 的数据库中创建一个表,其属性
    id为
    user_id(fk to user table)
    project_id(fk to project table)
  2. 当您创建项目时,还要使用给定字段填充 user_project。
  3. 制作它的模型,您将看到其中的关系。现在做一个像
public function getName()
{
return user->name;//here i have assumed that the relation name is user
}
  • 现在像这样查询这张表
$user=UserProject::mode::findAll();
$list=CHtml::listData($user,'user_id','name');

并使用此列表填充 dropDownList。这种方法的好处是不需要查询用户表的所有用户。

于 2014-02-28T20:57:48.570 回答