V
V
v0lume2014-05-03 18:48:06
Yii
v0lume, 2014-05-03 18:48:06

Yii all HAS_MANY relation condition?

Greetings
There is a Project
model Attributes: id, name
There is a Task
model Attributes: id, project_id, name, accepted
HAS_MANY relation (relation name - "tasks") from Task to (project_id => id) is added to Project.
The question is how to form a query using ActiveRecord in the search() method (you need to form a dataProvider for CListView + CPagination), which would select all Projects that have all tasks.accepted = 1 ?
PS
The whole difficulty lies in taking into account projects for which ALL tasks have been completed (and not at least one task)
Thank you for your attention :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2014-05-03
Protko @Fesor

The easiest option:

SELECT p.id, p.name, COUNT(t.id) as non_accepted_tasks FROM projects p 
LEFT JOIN tasks t ON t.project_id=p.id AND t.accepted <> 1 
GROUP BY t.project_id
HEAVING non_accepted_tasks = 0;

something like that.
There are also options with subqueries and inner join.

M
Maxim Grechushnikov, 2015-04-06
@maxyc_webber

public function getMembers($count = 100){
    return $this->hasMany(User::className(), ['id'=>'user_id'])
      ->limit($count)
      ->viaTable('users_clubs', ['club_id'=>'id'], function($query){
        $query->where(['status'=>User::STATUS_CLUB_JOINED_APPROVED]);
      });
  }

hasMany has a third callback parameter.
$this->hasMany(User::className(), ['id'=>'user_id'], function($query){ $query->where(['id'=>1]); })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question