【问题标题】:Laravel belongsTo Relationship returning null object from with methodLaravel 的 belongsTo 关系从 with 方法返回空对象
【发布时间】:2017-11-23 10:18:18
【问题描述】:

我想使用 jQuery 数据表制作一个列表。但是我对下面的用法有问题。

我的后备模型:

    //Reserve Author
    public function author(){

        return $this->belongsTo(User::class, 'author_id');

    }

    //Reserver
    public function reserver(){

        return $this->belongsTo(User::class, 'reserver_id');

    }    
    //Stock
    public function stock(){

        return $this->belongsTo(Stock::class, 'reference_id', 'code')->where('company_id', $this->company_id);

    }

以下使用成功

$reserve = Reserve::find(id);
$reserve->stock->name;

但这种用法不起作用:

Reserve::with('reserver','author', 'stock')->get()->toJson();

reserver 和 author 关系在此代码中有效,但 stock 返回 null 对象。我究竟做错了什么?如果你能帮助我,我会很高兴。谢谢。

【问题讨论】:

    标签: php json laravel-5.3 relationship belongs-to


    【解决方案1】:

    我以不同的方式解决了这个问题。我习惯了每种方法,现在正在工作。

    Reserve::with('reserver','author')->get()->each(function($q){
                    $q->setAttribute('stock', $q->stock->toArray());
                })->toJson();
    

    如果有更好的方法,我想使用它。谢谢。

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 2016-02-29
      • 2016-04-26
      相关资源
      最近更新 更多