2014-04-03 53 views
5

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

例如,我使用查询生成器如下可以得到我从数据库中需要的数据:

$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。

现在假设我有正确的雄辩关系设置,我将如何去做这个在雄辩?

这里是雄辩模型的相关部分

产品

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'); 
} 
} 

ProductType

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'); 
} 
} 

在此先感谢

回答

12

假设你的关系是正确的和相关的表名是:类别和类型,这将做的工作:

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

+0

谢谢你,现在是有道理的。 – Rob

+0

经过几个小时的无尽搜索,你节省了我的一天,谢谢。 – Sherif

-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