Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/247.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel 5.2-通过多个表连接_Php_Laravel_Laravel 5_Eloquent_Laravel 5.2 - Fatal编程技术网

Php Laravel 5.2-通过多个表连接

Php Laravel 5.2-通过多个表连接,php,laravel,laravel-5,eloquent,laravel-5.2,Php,Laravel,Laravel 5,Eloquent,Laravel 5.2,我有以下表格: User id Suggestions_For id user_id suggested_account Suggestions id (User.id = Suggestions_For.user_id) (Suggestions_For.suggested_account = Suggestions.id) 如果我想像这样获得用户的所有建议: $user->suggestions()->count() 我怎么做?有没有办法在我的

我有以下表格:

User
    id

Suggestions_For
    id
    user_id
    suggested_account

Suggestions
    id

(User.id = Suggestions_For.user_id)
(Suggestions_For.suggested_account = Suggestions.id)
如果我想像这样获得用户的所有建议: $user->suggestions()->count()

我怎么做?有没有办法在我的模型中定义一种关系,它通过多个透视表将用户加入到建议中

我试过:

public function suggestions()
{
    return $this->hasManyThrough('App\Suggestions', 'App\Suggestions_For', 'suggested_account', 'id');
}

但似乎不起作用

您可以将您的关系定义为使用透视表
建议作为

用户模型

public function suggestions()
{
    return $this->belongsToMany(Suggestions::class, 'suggestions_for', 'user_id')
}
建议模型

public function users()
{
    return $this->belongsToMany(User::class, 'suggestions_for', 'suggested_account ')
}

这似乎是一种简单的
manytomy
关系。还是我错了?我已经有一段时间没有接触过laravel了。@ariel先试试,在用户对象上你可以得到相关的建议,比如
$user->suggestions()->get()
同样地,在建议对象上你可以得到相关的用户
$suggestion->users()->get()
。我已经发布了一个使用pivot Table的多对多示例,错误是:在null上调用成员函数get(),$user->suggestions()返回null@ariel对不起,我忘记在
$this->belongtomany
之前添加
return
,太棒了,谢谢!!正确的代码是:public function suggestions(){return$this->belongsomany(suggestions::class,'suggestions\u for','user\u id','suggestive\u account')}