laravel连接表(如果存在数据)

Gre*_*nov 5 join laravel eloquent

如果表B中有数据,而不仅仅是表A中的数据,将表A与表B连接的最佳方法是什么?因为如果我以这种方式进行操作,并且表BI中没有照片,则不会从表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;
Run Code Online (Sandbox Code Playgroud)

我的想法只是提出另一个请求,以从表A中获取所有数据,其中category.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 | ... |
---------------------------------
Run Code Online (Sandbox Code Playgroud)

luk*_*ter 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']);
Run Code Online (Sandbox Code Playgroud)

或者你可以...

使用雄辩的力量

您只需要定义关系(我假设您已经有一个Photo模型),就可以轻松得多

class Category extends Eloquent {
    public function photos(){
        return $this->hasMany('Photo', 'cover_id');
    }
}
Run Code Online (Sandbox Code Playgroud)

然后...

$data = Category::with('photos')->get();
Run Code Online (Sandbox Code Playgroud)

您将把照片模型嵌套在类别模型中。可以这样访问:

foreach($data as $category){
    foreach($category->photos as $photo){
        echo $photo->filename;
    }
}
Run Code Online (Sandbox Code Playgroud)