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

标签 join laravel eloquent

如果表 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/

相关文章:

MySQL 连接优化问题

unit-testing - 如何模拟 Laravel Eloquent 模型的静态方法?

php - Laravel 中的三向关系

php - Foreach() 和 each() 内存不足,分块不起作用

php - 了解 : PHP + Redis + Node. js + 套接字之间的连接

php - Laravel Eloquent 操作集合

mysql join 查询提取仅阻止已关闭错误的 id

php - 通过单个查询获得类别和子类别

sql - 在同一日期或最接近的日期(之前或之后)连接两个表

laravel - Auth::check() 在 Laravel 5.7 的中间件中总是错误的