I have 2 models in my app, 'User' & 'MedicineType' (each User belongs to one MedicineType).
I made the one-to-many relation between two model using belongsTo() and hasMany(). hasMany() relation works perfectly but belongTo() doesn't work. Does anyone know where did I make a mistake?
User::find(1)->medicine_type [this returns nothing]
MedicineType::find(1)->users [this returns users]
Here's the code to Models:
class MedicineType extends Eloquent {
public function users()
{
return $this->hasMany('User');
}
}
class User extends Eloquent {
public function medicine_type()
{
return $this->belongsTo('MedicineType');
}
}
And here is my database structure:
users:
id
name
medicine_type_id
medicine_types:
id
name
Maybe there's an issue with Eloquent finding the foreign key. Try this:
EDIT:
Also, Eloquent tries to find the table "medicinetypes" and not "medecine_types", so you need to specify that as well using the
$table
variable.I change "medicine_type" to "medicineType" and everythings got OK...
I made the stupid mistake of not adding the "return" in the relationship method!
Make sure you return the relationship... Obviously this will not work:
The reason your relation is not working is not because of the relations specified in the model, but because of the method naming in the User model and not specifying the foreign key.
Instead of:
Use:
I hope this works for you ;)
Everything together:
and:
Testing if it works:
This successfully returns the related medicine_type's name.
I hope this helps you further ;)
In my case the related models data was deleted & laravel don't get soft deleted data in general query. To get soft deleted data you've to use "withTrashed() or onlyTrashed()".
You can check the documentation here.
https://laravel.com/docs/5.6/scout#soft-deleting