使用laravel eloquent连接两个数据库表

时间:2016-11-03 13:59:51

标签: json laravel-5 eloquent

我的数据库中有两个表:AgencyVehicle。每辆车属于一个机构,一个机构有很多车辆。这是我的模特:

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');
    }
}

现在我如何从控制器返回一个json对象,其中包含每个train及其相应的代理?我是否必须根据agency_id加入表格?这样做的最佳方式是什么?

感谢您的帮助:)

1 个答案:

答案 0 :(得分:1)

您可以使用with()toJson()作为:

进行尝试
Agency::with('trains')->get()->toJson();
相关问题