无法使 "One To Many" 关系在 Laravel 中起作用
Can't make "One To Many" relation work in Laravel
这是我的控制器函数中的代码:
$topic = Topic::create([
'title' => $request->input('title'),
'content' => $request->input('content'),
'tags' => $request->input('tags'),
]);
$forum = Forum::find($frid); // $frid = Forum ID
$topic->myforum($forum->id);// Not working
$topic->myforum($forum);// Not working
$topic->myforum()->associate($forum->id);// Not working
$topic->myforum()->associate($forum);// Not working
$topic->myforum()->attach($forum->id);// Not working
$topic->myforum()->attach($forum);// Not working
$topic->myforum = $forum;// Not working
$topic->myforum = $forum->id;// Not working
$topic->creator()->attach(Auth::user()->id);//Same Here
$topic->save();
主题模型:
public function myforum()
{
return $this->belongsTo('Forum', 'forum_id');
}
public function creator()
{
return $this->belongsTo('User', 'user_id');
}
论坛模型:
public function topics()
{
return $this->hasMany('Topic', 'forum_id');
}
用户模型:
public function topics()
{
return $this->hasMany('Topic', 'user_id');
}
所以正如您在控制器中看到的那样,我尝试了我在互联网上找到的所有可能性,但没有一种可行,所以请提供任何想法
而不是
return $this->hasMany('Topic', 'user_id');
我们应该使用
return $this->hasMany('App\Topic', 'user_id');
因为即使我们添加 use App\Topic;
它也不起作用,我们必须这样做
这是我的控制器函数中的代码:
$topic = Topic::create([
'title' => $request->input('title'),
'content' => $request->input('content'),
'tags' => $request->input('tags'),
]);
$forum = Forum::find($frid); // $frid = Forum ID
$topic->myforum($forum->id);// Not working
$topic->myforum($forum);// Not working
$topic->myforum()->associate($forum->id);// Not working
$topic->myforum()->associate($forum);// Not working
$topic->myforum()->attach($forum->id);// Not working
$topic->myforum()->attach($forum);// Not working
$topic->myforum = $forum;// Not working
$topic->myforum = $forum->id;// Not working
$topic->creator()->attach(Auth::user()->id);//Same Here
$topic->save();
主题模型:
public function myforum()
{
return $this->belongsTo('Forum', 'forum_id');
}
public function creator()
{
return $this->belongsTo('User', 'user_id');
}
论坛模型:
public function topics()
{
return $this->hasMany('Topic', 'forum_id');
}
用户模型:
public function topics()
{
return $this->hasMany('Topic', 'user_id');
}
所以正如您在控制器中看到的那样,我尝试了我在互联网上找到的所有可能性,但没有一种可行,所以请提供任何想法
而不是
return $this->hasMany('Topic', 'user_id');
我们应该使用
return $this->hasMany('App\Topic', 'user_id');
因为即使我们添加 use App\Topic;
它也不起作用,我们必须这样做