Laravel雄辩地没有获得多对多的相关表格

时间:2018-01-29 14:45:38

标签: laravel eloquent

我有OfferConntroller,我尝试从其他表中获取所有优惠(这是多对多的关系 - 正常工作)

提供型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;



class Offer extends Model
{
    protected $fillable = [
        'title', 'body'
    ];

    public function specialities()
    {
        return $this->belongsToMany('App\Speciality');
    }
}

专业模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Speciality extends Model
{
    // protected $table = 'specialities';

    protected $casts = [
        'speciality_id'=>'string'
    ];

    public function offers()
    {
        return $this->belongsToMany('App\Offer');
    }
}

specialities表格有name, id, offer_speciality表格有offer_id, speciality_id

我试图获得名字 所以在OffersController中:

public function index()
{
    return Offer::orderBy('created_at','desc')->with('specialities:name')->get();
}

我得到了空阵列&#34;专业&#34;纠正提取的优惠数组

1 个答案:

答案 0 :(得分:3)

更改方法的顺序:

Orders::with('specialities')->orderBy('created_at','desc')->get();