dqeonr8554 2017-04-26 21:27
浏览 61
已采纳

1到1的反向关系“belongsTo”给出了一个集合laravel而不是model

In my Profile model I setted this relationship

    public function lease()
{
    return $this->belongsTo(Lease::class, 'lease_id', 'id');
}

And in my Lease model I seeted this way

public function profile()
{
    return $this->hasOne(Profile::class, 'lease_id', id);
}

As longs as I know in laravel you could do

$profile = factory(App\Profile::class)->create();

$profile->lease()->get();

And then responds correctly with the model inside of a collection And if I do $profile->lease Responds correctly directly with the model

It isn't supposed that dynamic propertis execute the query right away like a shortcut of ->lease()->get()? Why it gives different formatted results?

  • 写回答

1条回答 默认 最新

  • dongzhenbi8919 2017-04-26 22:41
    关注

    When you are calling get on a builder you are getting a collection always. When you call first on a builder like that you will get a model or null. The dynamic property for the relationship, based upon the relationship object, will either query with get or first respectively when it loads it. Which is why $model->relationship is returning you the result you expect.

    The relationships that are singular, cause a find and the ones that are many cause a get.

    Laravel 5.4 - Docs - Eloquent - Relations - Relationship Methods vs Dynamic Properties

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题