我有需要执行的SQL查询:
SELECT users.FirstName, users.Id FROM `orders`
INNER JOIN orderrecipients ON orderrecipients.Orders_Id = orders.Id
INNER JOIN users ON users.Id = orderrecipients.Users_Id;
我尝试使用Eloquent模型通过hasManyThrough
构建以上查询:
public function OrderRecipients()
{
return $this->hasManyThrough('App\OrderRecipient', 'App\User', 'Id', 'Orders_Id');
}
使用的是:
$recipients = OrderModel::with("OrderRecipients")->where("User_Id", $userId)->get();
dd($recipients->OrderRecipients()->count());
如何建立这种关系并通过表获取数据?
答案 0 :(得分:0)
HasManyThrough
不是这里的最佳选择。请改用BelongsToMany
关系:
public function OrderRecipients()
{
return $this->belongsToMany('App\User', 'orderrecipients', 'Orders_Id', 'Users_Id');
}