简体   繁体   English

如何在Yii2中使用leftJoin从两个表中获取所有列数据

[英]How to get all column data from two tables by using leftJoin in Yii2

I tried to get books.id and authors.Name in an array using leftJoin() in Yii2. 我试图在books.id中使用leftJoin()在数组中获取books.idauthors.Name

$data = Book::find()
       ->select("authors.Name, books.id")
       ->leftJoin("authors", "authors.book_id = books.id")
       ->where(['books.id' => '14,16,17,18'])
       ->all();

But this result is only from books table. 但这个结果只来自books表。 I can not see authors.Name in this result. 我在这个结果中看不到authors.Name

In Laravel, it is easy to get the data like the above. 在Laravel中,很容易获得如上所述的数据。 Is it not possible in Yii2? 在Yii2中不可能吗?

By default all() returns array of related models and usually this models is not able to represent result of such query (for example Book model does not have Name field). 默认情况下, all()返回相关模型的数组,通常此模型无法表示此类查询的结果(例如, Book模型没有Name字段)。 Usually it is better to use asArray() - then all() will return list of arrays (which can store any kind of key-value pairs returned by query) instead of AR objects: 通常最好使用asArray() - 然后all()将返回数组列表(可以存储查询返回的任何类型的键值对)而不是AR对象:

$data = Book::find()
    ->select('authors.Name, books.id')
    ->leftJoin('authors', 'authors.book_id = books.id')
    ->where(['books.id' => '14,16,17,18'])
    ->asArray()
    ->all();

foreach ($data as $row) {
    echo "{$data['id']} - {$data['Name']}\n";
}

Or use Query directly: 或者直接使用Query

$data = (new Query())
    ->select('authors.Name, books.id')
    ->from(Book::tableName())
    ->leftJoin('authors', 'authors.book_id = books.id')
    ->where(['books.id' => '14,16,17,18'])
    ->all();

foreach ($data as $row) {
    echo "{$data['id']} - {$data['Name']}\n";
}

In your select clause ->select("authors.Name, books.id") you have not the columns authors.id and then the columns is not retrived from db. 在您的select子句->select("authors.Name, books.id")您没有authors.id列,然后列不会从db中重新获取。

so try adding this column too 所以尝试添加此列
and do the fact you have another id referer to the columns using a proper alias eg: autors_id 并使用适当的别名(例如:autors_id)为列提供另一个id referer

$data = Book::find()
       ->select("authors.Name, books.id, authors.id as authors_id")
       ->leftJoin(authors, "authors.book_id = books.id")
       ->where(['books.id' => '14,16,17,18'])
       ->all()

and be sure you have the same exact name for authors column name (normally the column name is lowercase ) 并确保您具有与作者列名相同的确切名称(通常列名称为小写)

 ->select("authors.name as authors_name, books.id, authors.id as authors_id")

amd be sure you have a correspondant field for receive the select result for author_name and author_id 并确保您有一个对应的字段来接收author_name和author_id的选择结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM