如何获得零售商b@gmail.com (价格表中的第5行)声明的最后一个价格,条件是角色=‘零售商’?
这是我的简单桌子:
表用户(使用模型中默认关系的信任角色包)
__________________________
| id | email | password |
|-------------------------|
| 1 | a@g.com | 123 |
| 2 | b@g.com | 123 |
| 3 c@g.com | 123 |
| 4 d@g.com | 123 |
--------------------------
表角色(使用模型中默认关系的信任角色包)
______________
|id | name |
|--------------|
|1 | customer |
|2 | retailer |
----------------
表role_user (使用模型中默认关系的信任角色包)
__________________
|id_user | id_role|
|------------------|
| 1 | 1 | -> a@gmail.com is a customer
| 2 | 2 | -> b@gmail.com is a retailer
| 3 | 1 | -> c@gmail.com is a customer
| 4 | 1 | -> d@gmail.com is a customer
------------------
下面是如何查询价格的棘手部分:
我有以下的价格表(用户可以张贴1或更多的价格。(看下面的关系):
____________________
|id| user_id| price |
|--------------------|
|1 | 1 | 10.00 | -> price claimed by a customer a@gmail.com
|2 | 2 | 5.00 | -> price claimed by a retailer b@gmail.com
|3 | 1 | 6.00 | -> price claimed by a previous customer a@gmail.com
|4 | 3 | 5.00 | -> price claimed by a customer c@gmail.com
|5 | 2 | 7.00 | -> price claimed by a previous retailer b@gmail.com //How to get this one? This is the last price claimed by the retailer.
|6 | 3 | 8.00 | -> price claim by a customer c@gmail.com
---------------------
我的价格模型中的关系:
class Price extends Model{
public function product()
{
return $this->belongsTo('App\Product');
}
public function user()
{
return $this->belongsTo('App\User');
}
如何获得零售商b@gmail.com (价格表中的第5行)声明的最后一个价格,条件是角色=‘零售商’?
目的是得到零售商声称的最后一个价格。
更新我的问题:,我想使用$products变量访问上一个零售商从产品模型中声明的价格。
我有一个示例表product:
_______________________________
|id | user_id| name |
|------------------------------
| 1 | 1 | Milk |
| 2 | 2 | Phone |
| 3 | 1 | computer |
| 4 | 1 | Banana |
------------------------------
我的Product.php模型关系:
class Product extends Model{
public function prices()
{
return $this->hasMany('App\Price');
}
}
因此,在我的ProductController.php中,我将$product变量发送到视图中,如下所示:
class ProductController extends Controller
{
public function show($id)
{
$product = Product::where('id', '=', $id)->
return view('products.show')->with('product', $product);
}
}
在我看来,show.blade.php,i循环遍历$product变量,我可以显示产品的报价。
@foreach($product->prices as $price)
<li>Price claimed: {{$price->price. " " }} </li>
@endforeach
我想像这样
$price_last = $product->prices()->where(role, 'retailer')->last().
dd($price_last);
函数--这是零售商声明的最后一个价格,但是这个代码只是一个例子。我怎样才能做到这一点?
如果你需要更多的信息,请告诉我。
发布于 2015-09-06 16:42:58
您正在寻找whereHas
方法:
$query = Price::latest('id')->whereHas('user', function ($query) {
$query->whereHas('role', function ($query) {
$query->where('name', 'retailer');
});
});
$price = $query->value('price');
这假设您已经设置了User
、Role
和Price
模型之间的关系。
https://stackoverflow.com/questions/32425845
复制相似问题