2015-08-20 37 views
0

後2天的尋找上laravel文檔和StackOverflow上沒有成功,我必須要問的問題多列「軸」表Laravel模型查詢

我有4款車型,到目前爲止,我試圖讓所有的相關信息一氣呵成。

用戶模式有關係:

public function transactions() { 
    return $this->hasMany('App\Transaction'); 
} 

賣場模式有關係:

public function transactions() { 
    return $this->hasMany('App\Transaction'); 
} 

產品型號有關係:

public function transactions() { 
    return $this->hasMany('App\Transaction'); 
} 

最後交易模式有關係:

public function user() { 
    return $this->belongsToMany('App\User'); 
} 
public function product() { 
    return $this->belongsToMany('App\Product'); 
} 
public function store() { 
    return $this->belongsToMany('App\Store'); 
} 

事務表(看起來像一個透視表):

transactions: 
    id - integer 
    user_id : integer 
    product_id : integer 
    store_id : integer 
    ....... some additional columns containing transaction specific data. 

我想有了這個,我得到的所有交易與引用細節auth用戶

又名「$用戶>交易」,然而我只能從相關表中獲取沒有數據。我也通過加入嘗試,但它看起來雜亂無章,我想有更好的得到這個數據結構良好的laravel

聯接貌似方式:

$transactions = DB::table('transactions as t')->where('user_id', Auth::id()) 
    ->join('products', 'products.id', '=', 't.product_id') 
    ->join('stores', 'stores.id', '=', 't.store_id') 
    ->get(array('t.id', 't.product_id', 'products.name as product_name', 't.store_id', 'stores.name as store_name')); 

我的目標是讓用戶對象的所有信息關於用戶包括交易和其他細節作爲一個JSON響應使用盡可能少的查詢。

回答

0

如果您的目標是獲取用戶對象,那麼您應該查詢用戶,而不是事務。

既然你已經定義了所有的關係,你可以利用查詢的雄辯,不需要手工做。

User::whereId(Auth::user()->id)->with('transactions','transactions.product','transactions.store')->get(); 
+0

感謝您的及時迴應我知道有這樣做的優雅方式。 我不知道是否有很好的方法來格式化響應,因爲在返回的對象中有很多不重要的信息。 (這個對象將被前端利用)。 – dascorp

+0

我會嘗試[** league/fractal **](http://fractal.thephpleague.com/)清除輸出 – dascorp