How do I perform joins with lithium models?

六眼飞鱼酱① 提交于 2019-11-28 01:28:35

问题


I read through lithium\data\model\query, but I didn't see any examples of joins.


回答1:


There are multiple ways to perform a join with Lithium.

  1. Lithium will handle joins for you where you have defined relationships (examples in the manual).
  2. You can add joins to an existing Query object using the join() method (see the API)).
  3. You can pass an array of Query objects to finders using the key joins.
  4. You can pass the SQL directly to a connection using Connection->read().

The other methods are reasonably well documented, so I'll give an example of passing Query objects to a finder.

$fields = array('id', 'name', 'slug');                                                                                                                                                                                                  
$joins = array();
$joins[] = new Query(array(
  'source' => 'client_tests',  
  'constraint' => array('Test.id' => 'client_tests.test_id'),
));
$conditions['client_id'] = $this->data['client_id'];
$tests = Test::all(array(
   'conditions' => $conditions,
   'fields' => $fields,
   'joins' => $joins
));

The source is the table that you want to join and constraint is the join criteria. Lithium aliases the find table to the name of the model, so use that in your constraint. You can then pass the joins in to any finder along with any other parameters you want.

Note that at the time of writing, joins (and relationships) will only work with a relational database, not for things like MongoDB's DBRef.

Update: Removed links that have been link jacked.




回答2:


If you set up a relationship (using hasOne, hasMany, or belongsTo) you can fetch the related data by supplying a with key in the options of your find call.

Like this:

$categories = Categories::find('all', array(
  'with' => 'Products'
));

Check out the manual chapter on Relationships for more detail.



来源:https://stackoverflow.com/questions/9391062/how-do-i-perform-joins-with-lithium-models

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!