[英]Laravel eloquent two has many relation
我已经尝试了太多次了,但还是没办法。 我正在尝试使用laravel制作自定义旅游应用程序。 我有3个模型,即用户-请求-报价用户有很多请求,请求有很多报价,但是报价和请求都属于用户,这是因为用户表有两个角色,一个是旅行者,一个是旅行代理商。
这是我的模型班用户
protected $fillable = [
'first_name',
'last_name',
'contact_number',
'photo',
'birthday',
'about',
'email',
'agency',
'logo',
'role',
'status_agency',
'is_admin',
'legal',
'password',
];
public function custom_tour_requests()
{
return $this->hasMany('App\custom_tour_request', 'traveler_id');
}
public function custom_tour_offers()
{
return $this->hasManyThrough('App\custom_tour_offer', 'App\custom_tour_request');
}
class custom_tour_request
protected $fillable = [
'title' ,
'departure' ,
'destination' ,
'description' ,
'start_date' ,
'end_date',
'budget' ,
'adult' ,
'child' ,
'traveler_id'
];
public function user()
{
return $this->belongsTo('App\user');
}
public function custom_tour_offers()
{
return $this->hasMany('App\custom_tour_offer', 'custom_tour_request_id');
}
class custom_tour_offer
protected $fillable = [
'title',
'departure',
'destination',
'itinerary',
'include',
'exclude',
'start_date',
'end_date',
'price'
];
public function custom_tour_request()
{
return $this->belongsTo('App\custom_tour_request');
}
public function user()
{
return $this->belongsTo('App\user');
}
每当我尝试插入它时返回错误,
$travelagent = user::find(Auth::user()->id);
$customtourRequest = $travelagent->custom_tour_offers()->create($requests->all());
我无法更改数据库设计。 我感到很困惑。
错误是什么? 您是否为此重新检查了文档和api? 也许您忘记了create方法之前的first()。
http://laravel.com/docs/5.0/eloquent#querying-relations
http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Relations/HasManyThrough.html
我个人喜欢这样做,例如custom_tour_offer::create($request->all());
试试这个并发布结果:
$tourOffers = $travelagent->custom_tour_offers();
$queryBuilder = $tourOffers->getQuery();
$sql = $queryBuilder->getGrammar()->compileInsert($queryBuilder, $requests->all());
dd($sql);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.