【发布时间】:2017-11-13 05:15:12
【问题描述】:
我目前正在学习 Laravel,但我遇到了一个我似乎无法找到解决方案的问题。我在两个表之间有一个多对多的关系,总是什么都不返回。让我向您展示基本设置:
我的帖子模特:
// App\Post.php
protected $fillable = [
'name',
'description'
'videopath'
];
public function Tags()
{
return $this->belongsToMany('App\Tag');
}
public function Cats()
{
return $this->belongsToMany('App\Cat');
}
我的标签模型:
// App\Tag.php
protected $fillable = [
'name',
'description'
];
public function exercises()
{
return $this->belongsToMany('App\Exercise');
}
我的帖子控制器:
// PostController.php
public function show($id)
{
$post = Post::find($id);
return view('posts', ['post'=>$post];
}
观点:
// posts.blade.php
@foreach($post->tags() as $tag)
//do stuff
@endforeach
中间表称为post_tag,包含post_id 和tag_id 列。起初它按预期返回了结果,但过了一段时间,我所有的帖子都不再返回任何标签了。猫模型看起来类似于标签模型。有人有想法吗?
【问题讨论】:
-
试试这个:
@foreach($post->Tags as $tag) -
请使用小写的函数名,例如
tags&cats