Error fetching model id and updating field using Laravel's HasManyThrough relationship
I have created 3 laravel Models Organization, User and Contact which have a Laravel HasManyThrough relationship.
I have defined all the necessary relationships for the models.
I need to update a specific field named "deletedate" for a contact belonging 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 function update_it (),
When fetching data, all contact fields that belong to that particular input "id" are retrieved except for the "id" field. Instead of extracting the contact ID, the user ID is exposed from two sides.
print $contact->name
This code returns the exact name of the contact belonging to the input id.
print $contact->id
So far, this code returns the user id.
$contact->save()
This code updates the delete field for a contact whose ID is user_id.
The three models are defined 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');
}
}
From the "Flash documentation" you can see that the method call find
retrieves all columns from the generated query. So in your case, you have two tables, joined contacts
and users
, and the users table is id
overwriting the contacts id
.
To receive only Contact fields, simply specify the required columns in the method find
as follows:
$contact = $this->organization->contact()->find(Input::get('id'), ['contacts.*']);
And then only contact information will be loaded, but it id
will be correct :)