我有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;纠正提取的优惠数组
答案 0 :(得分:3)
更改方法的顺序:
Orders::with('specialities')->orderBy('created_at','desc')->get();