【问题标题】:Joining two database tables with laravel eloquent使用 laravel eloquent 连接两个数据库表
【发布时间】: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 加入表格?最好的方法是什么?

感谢您的帮助:)

【问题讨论】:

    标签: json laravel-5 eloquent


    【解决方案1】:

    您可以使用with() 和toJson() 来尝试:

    Agency::with('trains')->get()->toJson();
    

    【讨论】:

      猜你喜欢
      • 2014-10-11
      • 2013-05-17
      • 2020-11-06
      • 2019-08-11
      • 1970-01-01
      • 2018-11-06
      • 2017-05-16
      • 2019-10-24
      • 2019-06-28
      相关资源
      最近更新 更多