这是我的表结构
使用者
ID 用户名 密码
命令
编号 user_id
订单详细信息
id product_id order_id
和关系都设置好了
User.php
function orders() {
return $this->hasMany('Order');
}
Order.php
function details() {
return $this->hasMany('OrderDetail');
}
OrderDetail.php
我获得了用户ID和产品ID,我想检查用户是否购买了此产品
User::find($userId)->orders()->details()->where('product_id', $productId)->count()
会出错,因为订单返回了多个数据,该如何检查?
您还无法通过Eloquent一次滑动来完成此操作。但是您可以轻松编写这样的函数来进行检查:
public function hasBoughtProduct($product_id, $user_id)
{
$orders = Orders::with('details')->where('user_id','=',$user_id)->get();
foreach($orders as $order)
{
$details = $order->details()->where('product_id', '=', $product_id)->count();
if($details > 0)
{
return TRUE;
}
}
return FALSE;
}
如果这不能满足您的需要,则可以考虑使用Fluent编写查询或覆盖newQuery()方法,以在其中预加入表。如果这更适合您,您可以参考此答案以获取有关如何执行此操作的更多详细信息:https : //stackoverflow.com/a/19183957/385402
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句