在视图中调用与参数的关系

calling relation with a parameter in the view

我知道很多人都问过这个问题,但是 none 的解决方案对我有用,因为我想在视图中使用它

我有3张桌子

Languages : id , title 
Blog : id 
BlogLanguage : blog_id , language_id , title , text 

所以当我在视图中列出博客时,我想为每个博客显示该博客存储了哪些语言

基本上我想做这样的事情

$blogs = Blog::all();
$languages = Language::all();
return view('blog-index' , compact('blogs' ,'languages));

在视图中

@foreach($blogs as $blog )

  id : {{$blog->id}} 
  @foreach($languages as $lang )
   {{$lang->title}} : {{ $lang->HasThisBlog($blog->id) ? 'yes' : 'no' }}
  @endforeach

@endforeach 

这是我卡住的地方

{{ $lang->HasThisBlog($blog->id) ? 'yes' : 'no' }}

如果我可以在语言模型中拥有这种关系

function HasThisBlog($id){
 return $this->hasOne(BlogLanguage::class )->where('blog_id' , $id ) ;
}

当然这不起作用,并且给了我一些奇怪的对象,比如

HasOne {#706 ▼
  #foreignKey: "blog_languages.language_id"
  #localKey: "id"
  #query: Builder {#705 ▶}
  #parent: Language {#560 ▶}
  #related: BlogLanguage {#667 ▶}
  #withDefault: null
}

您只需要在博客模型上定义一个关系。因为您已经为以下关系

设置了枢轴 table

博客属于多种语言

语言属于多个博客


class Blog extends Model
{
    public function languages()
    {
        return $this->belongsToMany(Language::class);
    }

    //....other code of the class
}

class Language extends Model
{
    public function blogs()
    {
        return $this->belongsToMany(Blog::class);
    }

    //... other code of the class
}

然后在blade视图中

@foreach($blogs as $blog)

    <p>{{ $blog->id }}</p>

    @foreach($languages as $language)
        <p>{{ $language->title }}: {{ $blog->languages->contains('id', $language->id) ? 'Yes' : 'No' }}</p>
    @endforeach

@endforeach