Eloquent laravel:获取表中所有关系的JSON表示

时间:2017-06-07 15:25:33

标签: php json laravel laravel-5 eloquent

模型 Ov.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Ov extends Model 
{

    protected $table = 'ov';
    public $timestamps = true;
    protected $fillable = array('version', 'macAddress');
    protected $hidden = array('timestamps');

    public function masters()
    {
        return $this->hasMany('App\Models\MasterEquipment', 'id_ov_foreign_key');
    }

}

模型 MasterEquipment.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class MasterEquipment extends Model 
{

    protected $table = 'masterEquipment';
    public $timestamps = true;
    protected $fillable = array('macAddress');

    public function slaveEquipments()
    {
        return $this->hasMany('App\Models\SlaveEquipment', 'id_masterEquipment_foreign_key');
    }

    public function equipment()
    {
        return $this->hasOne('App\Models\Equipment', 'id_masterEquipment_foreign_key');
    }

}

我想检索给定OV版本的整个JSON表示: 我试过了:

return Ov::where('version', '3')->with('masters')->get();

但它不起作用,我只得到以下JSON :(主人空着)

{
   "version": 3,
   "macAddress": "00:01:02:04:04",
   "masters":[]
}

你能帮我吗?

2 个答案:

答案 0 :(得分:0)

您需要为此使用Eloquent Resources

这很简单。无需返回模型,而是返回资源并将模型传递到资源集合中,如下所示:

return new OvCollection(Ov::where('version', '3')->with('masters')->get());

您必须首先创建资源集合。

答案 1 :(得分:0)

您的关系建立者是错误的。 从您的模型中,我得出结论,您的两个表是这样的

ov表

------------------------------
id   |  version  | macAddress
------------------------------

主设备表

---------------------
id   |  macAddress
---------------------

只有与两个表相关的内容是macAddress

所以您的情态关系应该是这样

卵巢模态

 public function masters()
    {
        return $this->hasMany(MasterEquipment:class, 'macAddress','macAddress);
    }

那么只有这将起作用

return Ov::where('version', '3')->with('masters')->get();