2016-12-16 267 views
0

我有5個表。Laravel雄辯5表

Users 
Categories 
Products 
Product_categories 
Order Details 

用戶購買一個項目,在我的訂單詳細信息表我店的數量等

我想回去是通過用戶主目錄=「測試」的所有項目。

$user = Auth::user(); 

return $user->items(); 

我在我的用戶模型上有以下關係。

public function items() 
    { 
     return $this->hasMany('App\OrderDetail','user_id')->selectRaw('item_description,count(quantity) as count')->where('item_description','<>','Carriage')->groupBy('item_id')->get(); 
    } 

我知道我已經不在這裏相關的類別表,但我不知道我會怎麼把所有的用戶命令的詳細信息,其中項目類別爲「測試」。該項目可以與許多類別相關,因此可以與product_categories表相關。

我不是有人在寫答案之後我想知道我在哪裏開始考慮通過模型鏈接這些問題?

我說我必須在我的模型關係中做一個函數嗎?

回答

3

根據您的要求&結構,你的表必須是這樣的:

users 
    id 
    name 
    ... 

categories 
    id 
    name 
    ... 

products 
    id 
    name 
    cost 
    ... 

category_product 
    id 
    category_id 
    product_id 

order_details 
    id 
    user_id 
    cost 
    ... 

product_order_detail 
    id 
    product_id 
    order_detail_id 

你的模型結構應當是這樣的:

class User extends Model 
{ 
    public function orderDetails() 
    { 
     return $this->hasMany(OrderDetail::class); 
    } 
} 

class Product extends Model 
{ 
    public function categories() 
    { 
     return $this->belongsToMany(Category::class, 'category_product'); 
    } 

    public function orderDetails() 
    { 
     return $this->belongsToMany(Order::class, 'product_order_detail'); 
    } 
} 

class Category extends Model 
{ 
    public function product() 
    { 
     return $this->belongsToMany(Product::class, 'category_product'); 
    } 
} 

class OrderDetail extends Model 
{ 
    public function user() 
    { 
     return $this->belongsTo(User::class); 
    } 

    public function products() 
    { 
     return $this->belongsToMany(Product::class, 'product_order_detail'); 
    } 
} 

,並獲取所有的項目/產品誰屬於名爲Testing的類別,屬於已訂購它的用戶:

$items = Product::whereHas('categories', function($q) { 
        $q->where('name', '=', 'Testing'); 
       })->whereHas('orderDetails', function($q) use($user) { 
        $q->whereHas('user', function($q) use($user) { 
         $q->where('id', $user->id); 
        }); 
       })->get(); 

希望這會有所幫助!