2016-12-16 274 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(); 

希望这会有所帮助!