【问题标题】:Cannot fetch data with hasMany eloquent relationship?无法通过 hasMany 雄辩的关系获取数据?
【发布时间】:2018-10-18 07:57:34
【问题描述】:

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

当我在 tinker 中运行查询时,它会显示错误。

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

它返回一个空数组 但如果我这样做:

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

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

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

【问题讨论】:

    标签: php laravel-5 orm eloquent


    【解决方案1】:

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

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

    试试这些,它会解决错误。

    【讨论】:

    【解决方案2】:

    使用这个:

    $usersWithPosts = User::has('posts')->get();
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 2015-01-29
    • 1970-01-01
    相关资源
    最近更新 更多