将表A与表B连接的最佳方法是什么,如果表B有数据,如果不是只给我表A中的数据?因为如果我这样做,并且表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 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 | ... |
---------------------------------
答案 0 :(得分:5)
只需使用leftJoin()
即可。普通("内部连接")将仅返回两个表的结果。但左连接会返回左表(在本例中为categories
)的所有结果以及其他表中存在的所有结果。
$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']);
或者你可以......
您只需要定义关系(我假设您已经拥有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;
}
}
答案 1 :(得分:0)
我宁愿这样做:
// Just assuming a few variables for better understanding
$allCategories = Category::all();
foreach ($allCategories as $category) {
$photo = Photo::find($category->cover_id);
if ($photo) { // $photo!=null or isset($photo) - you can use anything
// photo is found do the additional processing
}
//proceed with your normal processing
}