首页 文章

Laravel Eloquent和Multiple Joins

提问于
浏览
6

我理解如何使用Eloquent进行基本查询和关系,但是当我根据多个表中的关系选择信息时,我开始感到困惑 .

例如,我可以使用查询构建器从数据库中获取所需的数据,如下所示:

$data['products'] = DB::table('product')
    ->select('product.id', 'product.ref_num', 'productdetails.name')
    ->join('productdetails', function($join)
    {
        $join->on('product.id', '=', 'productdetails.product_id')
             ->where('productdetails.website_id', '=', '7');
    })
    ->leftJoin('product_category', function($join) use($submenu_id){
        $join->on('product.id', '=', 'product_category.product_id')
            ->where('product_category.category_id', '=', $submenu_id);
    })
    ->leftJoin('product_type', function($join) use($type_id){
        $join->on('product.id', '=', 'product_type.product_id')
            ->where('product_type.type_id', '=', $type_id);
    })
    ->get();

基本上,我从产品和产品详细信息表中获取数据,这些数据基于产品属于哪个类别以及产品类型;这些是通过内部连接到数据透视表product_type和product_category来定义的 .

现在假设我已经正确设置了雄辩的关系,我将如何在Eloquent中做到这一点?

以下是Eloquent模型的相关部分

产品

class Product extends Eloquent{

public function productdetails()
{
    return $this->hasMany('Productdetail');

public function categories()
{
    return $this->belongsToMany('Category', 'product_category', 'product_id', 'category_id');
}

public function types()
{
    return $this->belongsToMany('Producttype', 'product_type', 'product_id', 'type_id');
}
}

产品详情

class Productdetail extends Eloquent
{


public function product()
{
    return $this->belongsTo('Product');
}
}

产品类别

class ProductTypes extends Eloquent{


function products()
{
    return $this->belongsToMany('products', 'product_id', 'type_id', 'product_id');
}

类别

class Category extends Eloquent{

public function products()
{
    return $this->belongsToMany('product', 'product_category', 'category_id', 'product_id');
}
}

提前致谢

2 回答

  • 14

    假设您的关系是正确的并且相关的表名是:类别和类型,这将完成工作:

    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();
    

    它将运行2个查询(首先是获取相应的产品,第二个是与它们相关的产品详细信息)并返回Eloquent Collection

  • -2

    //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);
    

    视图

    @foreach($results as $result)
    {{ $result->image_1 }}
    @endforeach
    

相关问题