Laravel Eloquent and Multiple Joins

后端 未结 2 1723
梦如初夏
梦如初夏 2020-12-08 23:51

I understand how to use Eloquent for basic queries and relationships, but I start getting confused when selecting information based on relationships in multiple tables.

相关标签:
2条回答
  • 2020-12-09 00:27

    //routes.php

     /* relationship is : content has images(one to many). And I am extracting the images based on the name that is given in the search input ($keyword = Input::get('keyword') */
    
    
       $dbresults = DB::table('contents')->join('images', 'images.content_id', '=', 'contents.id')->where('contents.Name', 'LIKE', '%' .$keyword. '%')->get();
    
       return View::make('/results')->with("results", $dbresults);
    

    View

    @foreach($results as $result)
    {{ $result->image_1 }}
    @endforeach
    
    0 讨论(0)
  • 2020-12-09 00:28

    Assuming your relations are correct and related table names are: categories and types, this will do the job:

    Product::with('productdetails')
        ->whereHas('categories', function ($query) use ($submenu_id) {
              $query->where('categories.id', '=', $submenu_id);
        })
        ->whereHas('types', function ($query) use ($type_id) {
              $query->where('types.id', $type_id); // side note: operator '=' is default, so can be ommited
        })
        ->get();
    

    It will run 2 queries ( first for getting appropriate products, second for product details related to them) and return Eloquent Collection

    0 讨论(0)
提交回复
热议问题