douyong8801 2015-05-06 21:07
浏览 38
已采纳

通过Laravel 5.0中的关系访问属性

I have several models set up in a Grandparent -> Parent -> Child relationship, where each has a one-to-many relationship with the one beneath it. The backend is set up through migrations using the default created_at and modified_at dates, relevant as that is what I'm trying to grab records by.

I currently have (names replaced):

$parent->child->where('created_at', '=', $date);

Through echo'ing it out I can verify that $date is correct when the where function is run, and matches records in the database. My expectation based on documentation is that this should return a Collection. When I attempt to iterate through it to get each instance of the model inside, however, I get errors saying I'm attempting to access properties of a non-object. (Just trying to echo out the created_at date).

I also tried putting ->first() after the original, with the assumption that it would spit out the first child as an object, that matched those pre-requisites, however it comes out null despite the collection not showing as null when similarly tested.

My question is, is there a way to get the first() approach to work, returning a single instance of the model? Similar to:

$parent->child->where('created_at', '=', $date)->first();

This is my first time posting a question so if you need more info just ask.

  • 写回答

2条回答 默认 最新

  • dtjzpg5313 2015-05-07 01:08
    关注

    The issue you're having is due to the difference between:

    $parent->child;
    

    and

    $parent->child();
    

    The former ($parent->child) is a Collection of all the child objects, whereas the latter ($parent->child()) is the relationship query for the child objects.

    The sneaky problem you've hit is that both support the where() method, but their parameters are a little different. The parameters you're using would work fine for the where() method on the relationship query, but they are not correct for the where() method on the Collection, which is what you're using.

    You either need to switch to using the relationship query, or change your parameters to work with the where() on the Collection:

    $children = $parent->child->where('created_at', $date);
    // or
    $children = $parent->child()->where('created_at', '=', $date)->get();
    

    Note: the where() method on the Collection will filter the collection based on the field name ('created_at') being equal (== or ===) to the $date value. The third parameter will govern the strictness (default is strict (===), or use false for loose (==)).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀