2014-10-30 89 views
2

在控制器中,我想传递唯一的一个变量,并在其中指定来自父项的列。现在,我使用Laravel:使用雄辩的属性,从两个表中获取数据?

View::make('store.product')->with('products', Product::find($id) 
->join('design','product.design_id','=','design.id') 
->join('user','design.user_id','=','user.id') 
->select('user.name','design.title','product.price') 
->get(); 

我的问题是

1.Is有更好的方法,通过使用属于关联做到这一点?

2.如果可以,Hasmany的工作原理是否相同?

这是我的表格结构。

用户

id | name 
1 | 'John' 

设计

id | user_id | title 
1 | 1 | 'Chill' 
2 | 1 | 'Mad' 

产品

id | design_id | price 
1 |  1  | 20 
2 |  1  | 30 

和型号是这样的

产品属于关联设计设计属于关联用户

回答

4

添加一个方法给您的用户,像这样为你设计,用户有;

public function designs(){ 
    $this->hasMany('Design'); 
} 

对于设计模型添加以下方法;

public function user(){ 
    $this->belongsTo('User'); 
} 

public function products(){ 
    $this->hasMany('Product'); 
} 

为您的产品型号

public function design(){ 
    $this->belongsTo('Design'); 
} 

这些将建立关系,让你渴望负荷您的模型中的数据。

这可以这样做;

$variable = Product::with('designs')->find(1); //This will load the product with the related designs 

如果您希望属于设计的所有设计和用户执行以下操作;

$variable = Product::with('designs', 'design.user')->find(1); //This will load the designs that relate to the Product and include the user that that design belongs to on the Design model. 

要访问属性,请使用以下内容;

$variable->designs //This will return a collection of all the designs. 
$variable->designs->first()->user //This will return the user model that the design belongs to. 

显示信息的示例;

@foreach ($variable->designs as $design) 
    {{ $design->user->username }} 
@endforeach 

请注意:我还没有测试过这个代码。

+0

几乎在那里!如果我也想要一个相关用户,可以这样做吗? – Johny 2014-10-30 15:20:40

+0

@Johny编辑以显示如何访问信息。为了获得相关用户以及使用Product :: with('designs','design.user') - > find(1); – 2014-10-30 15:37:35

+0

NEAT !!完美的作品!非常感谢你马特。 – Johny 2014-10-30 15:56:35