php - Laravel Eloquent relation not retrieving data from related table
问题描述
Iv got a simple "publications" table and "Languages" table as seen below. All I want to do is output "available languages" associated with the publication. iv tried relationships this way and that and cnt get it right
Controller:
public function index()
{
$publications = Publication::all();
$languages = Language::all();
return view('admin/publications/index', compact('publications', 'languages'));
}
Publication Model relationship:
public function languages(){
return $this->hasMany('App\Language');
}
Please help!
解决方案
Use with
to include relations:
public function index()
{
$publications = Publication::with('languages')->get();
return view('admin/publications/index', compact('publications'));
}
This allows you to then access the related models like:
foreach ($publication->languages as $language) {
echo $language->myAttribute;
}
推荐阅读
- ember.js - 如何在 Ember 中使用Html 之类的 void 链接
- tinymce - TinyMCE 表默认属性
- java - Try-catch 打印堆栈跟踪
- pine-script - Pinescript v4 更改功能
- github-actions - github 操作:在全局环境部分中使用变量
- html - 如何切换按钮内文本的颜色
- shopify - 在 shopify 中自动调整 Chekout 顶部横幅图像的大小
- swift - 如何从 AVCaptureSession 访问像素值
- python - 使用 openpyxl 查找匹配的字符串并填充数据
- c# - 使用值 EF Core 将字段设为下拉列表