Laravel join table if data exists

What is the best way to join table A with table B if there is data in table B, and if not just give me the data from table A? because if I do it this way and there are no photos in table B, I do not get the data from this row from table 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;

My idea is to make another request to get all the data from table A, where category.cover_id is 0 (no connection)

my tables are just

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 | ... |
---------------------------------
+4
source share
2 answers

, leftJoin(). ( " " ) . left join ( 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;
    }
}
+4

:

// 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
}
0

Source: https://habr.com/ru/post/1569102/


All Articles