【发布时间】:2016-11-03 13:59:50
【问题描述】:
我的数据库中有两个表:Agency 和 Vehicle。每辆车都属于一个机构,一个机构有很多辆车。这是我的模型:
Agency模特:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Agency extends Model
{
protected $fillable = ['name', 'location'];
public function trains(){
return $this->hasMany('App\Vehicle');
}
}
Vehicle模特:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Vehicle extends Model
{
protected $fillable = [
'agency_id',
'registration_number',
'description'
];
public function agency(){
return $this->belongsTo('App\Agency');
}
}
现在如何从我的控制器返回一个包含每个 train 及其相应代理的 json 对象?我是否必须根据 Agency_id 加入表格?最好的方法是什么?
感谢您的帮助:)
【问题讨论】: