如何通过表检索信息?

时间:2018-11-30 23:03:06

标签: laravel laravel-5

我有需要执行的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());

如何建立这种关系并通过表获取数据?

1 个答案:

答案 0 :(得分:0)

HasManyThrough不是这里的最佳选择。请改用BelongsToMany关系:

public function OrderRecipients()
{
    return $this->belongsToMany('App\User', 'orderrecipients', 'Orders_Id', 'Users_Id');
}