想象一个数据库,其中每个Product与Account表都有关系。
如果我使用
joinWith()
方法提出请求
$products = Product::find()->joinWith('account')->asArray()->all();
我会得到这样的东西:
[
'title' => 'Product title',
'price' => 'Product price',
'accountId' => 1
'account' => [
'id' => 1,
'name' => 'Account name',
'location' => 'Account location'
]
]
可以看到子数组中记录了来自account表的数据。
使用函数
leftJoin()
是否可以达到相同的结果?这就是我尝试做的事情:
$products = Product::find()
->select('Product.*')
->leftJoin('Account', 'Account.id = Product.accountId')
->addSelect([
'Account.name as accountName',
'Account.location as accountLocation',
])
->all();
在这种情况下,结果将是:
[
'title' => 'Product title',
'price' => 'Product price',
'accountId' => 1,
'accountName' => 'Account name',
'accountLocation' => 'Account location'
]
是否可以
leftJoin()
表,以便连接表的结果位于子数组中?
尝试将 ->with('account') 添加到您的查询中。
$products = Product::find()
->select('Product.*')
->leftJoin('Account', 'Account.id = Product.accountId')
->with('account')
->addSelect([
'Account.name as accountName',
'Account.location as accountLocation',
])
->all();
根据 Yii2 文档,直接通过 joinWith() 方法加载关系是更好的方法,就像您在第一个示例中使用的那样。 使用关系数据