简体   繁体   English

Laravel 4.1处理多对多关系

[英]Laravel 4.1 working with many-to-many relationships

I have a Post model with the following function: 我有一个具有以下功能的Post模型:

public function tags() {

    return $this->belongsToMany('Tag', 'refs', 'post', 'tag');

}

And a Tag model with a similar function: 以及具有类似功能的Tag模型:

public function posts() {

    return $this->belongsToMany('Post', 'refs', 'tag', 'post');

}

Now I'm outputting my tags as checkboxes in a foreach loop. 现在,我将标签输出为foreach循环中的复选框。 What I'm then interested in doing is checking the boxes corresponding to tags that are related to the Post model I'm working with in the given view, but intuition did not solve the issue for me, and I don't know enough technical jargon to formulate a proper search query for an answer on Google. 然后,我有兴趣做的是在给定视图中选中与与我正在使用的Post模型相关的标签相对应的框,但是直觉并不能解决我的问题,而且我对技术不够了解用行话来为Google的答案制定适当的搜索查询。

EDIT: 编辑:

In case of relevance this is my foreach loop: 如果相关,这是我的foreach循环:

    @foreach($tags as $tag)
        <tr>
        <td><label for="{{ $tag->id }}">{{ $tag->title }}</label></td>
        <td><input type="checkbox" value="{{ $tag->id }}" name="tags[]" id="{{ $tag->id }}" /></td>
        </tr>
    @endforeach

Which works perfectly. 哪个完美。 I just need to figure out what my if-statement should be for outputting the following at the end of my input tag in the correct loops. 我只需要弄清楚我的if语句应该在正确的循环中在我的输入标签的末尾输出以下内容。

checked="checked"

Sounds like you want something like this: 听起来您想要这样的东西:

<input type="checkbox" value="{{ $tag->id }}" name="tags[]" id="{{ $tag->id }}" @if ($post->tags->contains($tag->id)) checked="checked" @endif />

So, basically, if the Post 's collection of Tag s contains the Tag 's id, the checkbox will be checked. 因此,基本上,如果PostTag集合包含Tag的ID,则将选中该复选框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM