首页 > 解决方案 > 无法通过 hasMany 雄辩的关系获取数据?

问题描述

我正在努力学习雄辩的人际关系。我的关系是这样的:用户有很多帖子,一个帖子属于一个用户。

当我在修补程序中运行查询时,它会显示错误。

$user->new User();
$user->all(); //Displays all the users
but i cannot do
$user->all()->posts;

它返回一个空数组 ,但如果我执行以下操作:

$posts = new Post();
$posts->all();
$post->users;

错误:带有消息“此集合实例上不存在属性 [post]”的异常。

我怎样才能实现像我想让用户与帖子相关联的东西,或者确切地说我想要写过帖子的用户。

标签: phplaravel-5ormeloquent

解决方案


根据您编写的代码,新用户缺少括号。应该是这样的

$user = new User();// Initialize the user model class
$user->all(); //get all users
$userpost =  $user->posts // link the user model to the post

尝试这些它将解决错误。


推荐阅读