php - 使用视图中的参数调用关系
问题描述
我知道这已经被问了很多,但是没有一个解决方案对我有用,因为我想在视图中使用它
我有 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
}
解决方案
你只需要在你的博客模型上定义一个关系。因为您已经有以下关系的数据透视表
博客属于多种语言
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
推荐阅读
- firebase - Firebase 部署错误:y 中的编译错误:[E] 1:1 - 输入不匹配 '{' 期望 {'function'、'service'、'rules_version'}
- typescript - 解构数组正在从类型中删除可能的未定义值
- android - 在单元测试中覆盖类
- python - 带有通用 ELSE 子句的 IF 语句
- javascript - 如何在重复的某个字符后删除获取子字符串
- reporting-services - SSRS 从另一个数据集填充一个数据集的列
- css - 当我将页脚放在页面底部时,它位于页面中间
- excel - 下拉从宏中选择网络
- video - 如何检测另一个视频中是否存在视频轨道
- python - 如何修复“CreateView 缺少查询集”