【问题标题】:Laravel Many-To-Many relation returns no resultsLaravel 多对多关系不返回结果
【发布时间】: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_idtag_id 列。起初它按预期返回了结果,但过了一段时间,我所有的帖子都不再返回任何标签了。猫模型看起来类似于标签模型。有人有想法吗?

【问题讨论】:

  • 试试这个:@foreach($post->Tags as $tag)
  • 请使用小写的函数名,例如tags & cats

标签: php laravel laravel-5


【解决方案1】:
  1. 检查标签函数的名称。在您看来,您调用的是“tags”而不是“Tags”。

  2. 您是否在数据库中创建了中间表?如果是这样,请检查 Laravel 用来查找它的命名约定(字母顺序):在您的情况下,它应该是 tag_post。如果没有,customize the name of the table when defining the relationship.

多对多

多对多关系比 hasOne 和 hasMany 关系稍微复杂一些。这样的一个例子 关系是具有许多角色的用户,其中角色也是 由其他用户共享。例如,许多用户可能具有以下角色 “行政”。为了定义这种关系,三个数据库表是 需要:usersrolesrole_userrole_user 表派生自相关模型名称的字母顺序,并包含 user_idrole_id 列。

【讨论】:

  • 实际上是我错过了一个中间表。哇。这对我来说很愚蠢。非常感谢。
  • @NurullahYel 很高兴为您提供帮助。
【解决方案2】:

接受你的看法:

@foreach($post->tags() as $tag)
    //do stuff
@endforeach

$post->tags() 将返回关系而不是实际集合。你想要$post->tags$post->tags()->get()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2016-10-26
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多