laravel-5 - 使用 laravel 在 hasMany 关系中用外键覆盖主键
问题描述
这是我的桌子
Posts
id | name | created_At
Comments
id | comment | post_id | created_at
后模型
function comments(){
return $this->hasMany('App\Models\Comment','id','post_id');
}
帖子控制器
function index()
{
Post::with('comments')::get();
}
现在我怎样才能得到所有帖子的列表以及评论?
我正在尝试匹配子表中的 post_id。
解决方案
在您的帖子模型中:
public function comments()
{
return $this->hasMany('App\Model\Comment');
}
在您的后期控制器中:
use Illuminate\Http\Request;
function index(Request $request)
{
$posts=Post::with('comments')->get();
// in json
return response()->json($posts);
// in your view
//return view('viewname')->with('posts',$posts);
}
推荐阅读
- wpf - 如何使用 TopLevelItem (MenuItemRole)
- node.js - 使用 ESM 时如何在 Node.js 中自动重新加载文件?
- node.js - 尝试将 Qlik Sense 应用程序序列化为 JSON 对象时出错
- python - 如何使用 python 使用维度时间、纬度、长 netcdf 进行切片
- java - 无法启动 Hybris 服务器
- vue.js - 如何跟踪存储在 Vuex(store) 中的属性的变化并根据该值执行一些方法?
- python - image.save() 不保存具有指定名称的文件
- python-3.x - 如何在 Python3/PyQt5 中以超链接格式显示程序的输出结果?
- ios - 如何为 React Native iOS UI 组件扩展 UIViewController?
- javascript - 如何使用 Chrome 浏览器在 ASP.Net 中停止将输入类型自动填充为密码