如果表 B 有数据并且不只提供表 A 中的数据,那么将表 A 与表 B 连接的最佳方式是什么?因为如果我这样做,并且表 B 中没有照片,我就无法从表 A 中获取该行的数据。
$data = Category::join('photos', 'categories.cover_id', '=', 'photos.id')
->get(['categories.id',
'categories.position',
'categories.visible',
'categories.created_at',
'categories.updated_at',
'categories.title',
'photos.filename']);
return $data;
我的想法只是发出另一个请求以获取表A中的所有数据,其中categories.cover_id为0(没有连接)
我的 table 只是
table A (categories)
-------------------------------
| id | title | cover_id | ... |
-------------------------------
| 1 | lorem | 1 | ... |
-------------------------------
| 2 | ipsum | 12 | ... |
-------------------------------
| 3 | dolor | 0 | ... |
-------------------------------
table B (Photos, there is no data for dolor, because i created dolor recently in table A)
---------------------------------
| id | title | filename | ... |
---------------------------------
| 1 | lorem | lorem.jpg | ... |
---------------------------------
| .. | ..... | ...jpg | ... |
---------------------------------
| 12 | ipsum | ipsum.jpg | ... |
---------------------------------
最佳答案
只需使用 leftJoin()
就可以了。普通(“内连接”)只会返回两个表的结果。但是左联接返回左表(在本例中为类别
)中的所有结果以及另一个表中存在的所有内容。
$data = Category::leftJoin('photos', 'categories.cover_id', '=', 'photos.id')
->get(['categories.id',
'categories.position',
'categories.visible',
'categories.created_at',
'categories.updated_at',
'categories.title',
'photos.filename']);
或者你可以...
利用 Eloquent 力量
您只需要定义关系(我假设您已经有一个 Photo
模型),这会变得容易得多
class Category extends Eloquent {
public function photos(){
return $this->hasMany('Photo', 'cover_id');
}
}
然后...
$data = Category::with('photos')->get();
您将把照片模型嵌套在类别模型中。可以像这样访问:
foreach($data as $category){
foreach($category->photos as $photo){
echo $photo->filename;
}
}
关于join - laravel 连接表(如果数据存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27664377/