2014-10-30 86 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