Home Laravel eloquent two has many relation
Reply: 2

Laravel eloquent two has many relation

Brian lee
1#
Brian lee Published in 2015-06-20 21:02:06Z

I've tried it too many times but I still can't get it. I am trying to make a custom tour app with laravel. I have 3 models which is User - Request - Offer User has many requests, request has many offers but the offer and request both belong to user, it is because of the user table have two roles, one as a traveler and one as a travel agents.

here is my model class user

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

Whenever I tried to insert it return error,

$travelagent = user::find(Auth::user()->id);        
$customtourRequest =   $travelagent->custom_tour_offers()->create($requests->all());

I can't change my database design. I am so confused.

Spycomb
2#
Spycomb Reply to 2015-06-20 23:07:48Z

whats the error? have you re-check the docs and the api for that? maybe you forgot the first() before the create method.

http://laravel.com/docs/5.0/eloquent#querying-relations

http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Relations/HasManyThrough.html

i personally like to do it like custom_tour_offer::create($request->all());

Hkan
3#
Hkan Reply to 2015-06-21 18:31:02Z

Try this and post the results:

$tourOffers = $travelagent->custom_tour_offers();
$queryBuilder = $tourOffers->getQuery();
$sql = $queryBuilder->getGrammar()->compileInsert($queryBuilder, $requests->all());

dd($sql);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.296419 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO