Arun D
Arun D

Reputation: 2387

Error in fetching id of a model and updating a field using the Laravel HasManyThrough relation

I have created 3 laravel models Organization, User & Contact which have a Laravel HasManyThrough relation.

I have defined all the required relationships for the Models.

I have to update a specific field named 'deletedate' of a contact which belongs to an Organization.

I used the following code:

class ContactsController extends BaseController
{
    function __construct()
    {
        $this->user= User::find(Auth::id());
        $this->organization = $this->user->organization;
    }

    public function update_it()
    {
        $contact = $this->organization->contact()->find(Input::get('id'));

        $contact->deletedate = Carbon\Carbon::now()->toDateTimeString();

        print $contact->name;

        print $contact->id;

        $contact->save();
    }
}

In the function function update_it(),

While fetching the data, all the fields of a contact which belongs to that specific Input “id” is extracted except the field “id”. Instead of fetching the id of the Contact, the id of User is bieng fetched.

print $contact->name This code returns the exact name of the contact that belongs to the input id.

print $contact->id While this code returns the id of the User.

$contact->save() This code updates the contact's “deletedate” field whose id is equal to user_id.

Defenition of the three models is given below:

Organization Model :

class Organization extends Eloquent 
{       
    protected $table = 'organizations';

    public function contact()
    {
        return $this->hasManyThrough('Contact', 'User', 'organization_id', 'user_id');
    }
}

User Model:

class User extends Eloquent 
{
    protected $table = 'users';
    public function contact()
    {
        return $this->hasMany('Contact');
    }

    public function organization()
    {
        return $this->belongsTo('Organization');
    }
}

Contact Model:

class Contact extends Eloquent 
{
    protected $table = 'contacts';
    public function user()
    {
        return $this->belongsTo('User');
    }
}

Upvotes: 3

Views: 163

Answers (1)

Sh1d0w
Sh1d0w

Reputation: 9520

From the Eloquent documentation you can see that calling the find method fetches all columns from the query generated. So in your case you have two tables joined contacts and users and users table id overwrites the contacts id.

In order to fetch only Contact fields, just specify the columns you want in find method like this:

$contact = $this->organization->contact()->find(Input::get('id'), ['contacts.*']);

And then you will have only contact data loaded and the id will be the correct one :)

Upvotes: 4

Related Questions