首页 > 解决方案 > 使用视图中的参数调用关系

问题描述

我知道这已经被问了很多,但是没有一个解决方案对我有用,因为我想在视图中使用它

我有 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
}

标签: phplaravellaravel-5.8

解决方案


你只需要在你的博客模型上定义一个关系。因为您已经有以下关系的数据透视表

博客属于多种语言

Language belongsToMany 博客


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
}

然后在刀片视图中

@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

推荐阅读