我有两张桌子:汽车和用户
汽车可以有一个所有者 - >外键给表用户和驱动程序(可以与所有者不同) - >也是用户的外键
假设我有一个使用此查询的特定原因:
$cars= json_encode($this->Cars->get($carsid[0]['id'], [ 'contain' => ['Color','Model'] ]),JSON_HEX_APOS);如果我添加'用户'包含我会得到所有者用户,而不是驱动程序
我如何获得驱动程序?
我试过innerJoin和匹配,但它似乎与get方法一起工作
I have two tables: cars and users
A car can have an owner -> Foreign key to table users and the driver (can be different from owner) -> Also foreign key to users
Let's say I have a specific reason to use this query:
$cars= json_encode($this->Cars->get($carsid[0]['id'], [ 'contain' => ['Color','Model'] ]),JSON_HEX_APOS);if I add 'Users' in contain I'll get the owner user and not the driver
How can I get the driver?
I've tried innerJoin and matching but it does seem to work with the get method
最满意答案
手册说
如您所见,通过指定className键,可以将同一个表用作同一个表的不同关联。 您甚至可以创建自我关联的表来创建父子关系:
所以你可以做
class CarssTable extends Table { public function initialize(array $config) { $this->belongsTo('Users', [ 'className' => 'Users', ]); $this->belongsTo('Drivers', [ 'className' => 'Users', ]); } }所以你可以做
'contain' => ['Drivers', 'Models' ...]the manual says
As you can see, by specifying the className key, it is possible to use the same table as different associations for the same table. You can even create self-associated tables to create parent-child relationships:
so you can do
class CarssTable extends Table { public function initialize(array $config) { $this->belongsTo('Users', [ 'className' => 'Users', ]); $this->belongsTo('Drivers', [ 'className' => 'Users', ]); } }so you can do
'contain' => ['Drivers', 'Models' ...]更多推荐
发布评论