laravel relationship between 5 tables - laravel

I have 5 tables User, Profile, Address,State,City .Need to create relationship between tables.Address has State id , City id and Profile id in the table.Profile has User Id in the table.City has State Id in the table. How to write relationship between table
class City extends Model
{
public function state() {
return $this->belongsTo('App\State');
}
public function addresses() {
return $this->hasMany('App\Address');
}
}
class State extends Model
{
public function cities() {
return $this->hasMany('App\City');
}
public function addresses() {
return $this->hasMany('App\Address');
}
}
class Profile extends Model
{
public function address() {
return $this->belongsTo('App\Address');
}
public function user() {
return $this->belongsTo('App\User');
}
}
class Address extends Model
{
public function profile() {
return $this->belongsTo('App\Profile');
}
public function city() {
return $this->belongsTo('App\City');
}
public function state() {
return $this->belongsTo('App\State');
}
}
// users table
public function profile(){
return $this->hasOne('App\Profile');
}

Generally your model design is true, i have edited a few parts. Try the codes below.
class City extends Model
{
public function state()
{
return $this->belongsTo('App\State');
}
public function addresses()
{
return $this->hasMany('App\Address');
}
}
class State extends Model
{
public function cities()
{
return $this->hasMany('App\City');
}
public function addresses()
{
return $this->hasMany('App\Address');
}
}
class Profile extends Model
{
public function addresses()
{
return $this->hasMany('App\Address');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
class Address extends Model
{
public function profile()
{
return $this->belongsTo('App\Profile');
}
public function city()
{
return $this->belongsTo('App\City');
}
public function state()
{
return $this->belongsTo('App\State');
}
}
class User extends Model
{
public function profile()
{
return $this->hasOne('App\Profile');
}
}
By the way, Laravel relationships add default keys according to your method names. If you have problem about it you can find info from official documents. For example:
$this->belongsTo('App\Model', 'foreign_key', 'other_key');

as #mustafa.akcoban says...
When you use belongsTo Eloquent will work as follow
$this->belongsTo('App\City', 'foreign_key', 'other_key');
// foreign_key = is the primary key in the related model, by default 'id' for Eloquent
// other_key = is the field in the current model that contains the id of the other model, by default othermodelname_id for Eloquent
// For eg. 'App\City', 'id', 'city_id'
When you use hasMany Eloquent works as follow
$this->hasMany('App\Model', 'currentmodel_id', 'primary_key');
// currentmodel_id = is the field that contains the current model primary key in the related model
// primary_key = is the current primary key model that will be in the other model, by default id for Eloquent
// For eg. 'App\City', 'state_id', 'id'
Remember you can or can't use second and third parameter, if something is wrong Laravel dump will tell you what column was not found in the table, and you will can fix.
Please try and practice this, and let me know how it works :)

Related

Laravel relationship "fallback"

class Price extends Model {
public function priceable() {
return $this->morphTo();
}
}
class Venue extends Model {
public function events() {
return $this->hasMany('App\Event');
}
public function price() {
return $this->morphOne('App\Price', 'priceable');
}
}
class Event extends Model {
public function venue() {
return $this->belongsTo('App\Venue');
}
public function price() {
return $this->morphOne('App\Price', 'priceable');
}
}
What is the best way to have a fallback, if the event doesn't have a price assigned, to get it to use the event's venue price?
Is there a logical way to make this as a relation or should I just do everything in the Controllers?
You can set a default model with optional custom values directly from the relation. This default model can be populated either from an array or an anonymous function:
public function price()
{
return $this->morphOne('App\Price', 'priceable')->withDefault([...]);
}
You can refer to Laravel's documentation about default models for some more explanation.
class Event extends Model {
...
public function getEventPriceAttribute() {
return $this->price > 0 ? $this->price : $this->venue()->price
}
...
}
By doing this, you can call Event object and get the price like this:
$eventObject->eventPrice;

Relationship through one model

I have three tables - users, properties, devices.
users
id
name
properties
id
name
user_id
devices
id
name
property_id
How to define straight relationship to user model from devices model?
class Device extends Model
{
public function user()
{
return $this->....();
}
}
Is it possible to define such relation? Thanks.
Make sure to set all relation in other classes.
class Property extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
class Device extends Model
{
public function property()
{
return $this->belongsTo('App\Property');
}
public function user()
{
return $this->belongsTo('App\User', null, null, 'property');
}
}
You can provide a relation with in 4th parameter of belongsTo method.
//user model
public function role()
{
return $this->belongsTo('App\Role');
}
public function employee()
{
return $this->hasMany('App\Employee');
}
//role model
public function users()
{
return $this->hasMany('App\User');
}
//employee model
public function users()
{
return $this->belongsTo('App\User');
}
//value show using tinker command in command promote
App\User::find(1)->employee;
App\User::find(1)->role;
I think I have found the solution, this is what I end up with.
class Device extends Model
{
public function user()
{
$instance = new User();
$instance->setTable('properties');
$query = $instance->newQuery();
return (new BelongsTo($query, $this, 'property_id', $instance->getKeyName(), 'property'))
->join('users', 'users.id', '=', 'properties.user_id')
->select(DB::raw('users.*')
);
}
}
Hope this will be of help for somebody.

Complex relationship formation in Laravel 5

I'm working on a complex shopping cart project. I have relationships like this
CategoryGroup model
// App\CategoryGroup
class CategoryGroup extend Model
{
public function categories()
{
return $this->hasMany(Category::class);
}
}
Category model
// App\Category
class Inventory extend Model
{
public function categoryGroup()
{
return $this->belongsTo(CategoryGroup::class);
}
public function products()
{
return $this->belongsToMany(Product::class);
}
public function listings()
{
return $this->belongsToMany(
Inventory::class,
'category_product',
null,
'product_id',
null,
'product_id'
);
}
}
Product model
// App\Product
class Product extend Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
public function listings()
{
return $this->hasMany(Inventory::class);
}
}
Inventory model
// App\Inventory
class Inventory extend Model
{
public function products()
{
return $this->belongsTo(Product::class);
}
}
Now I'm stuck on the situation where I need to create a relationship between The CategoryGroups and the Inventory model like this:
// App\CategoryGroup
class CategoryGroup extend Model
{
public function categories()
{
return $this->hasMany(Category::class);
}
public function listings()
{
// Can't figured out the way
// A belongsToMany like the App\Category would be great
}
}
Is there a good way to achieve this kind of relationship?
Laravel has no native support for a direct relationship.
I created a package for cases like this: https://github.com/staudenmeir/eloquent-has-many-deep
You can use it like this:
class CategoryGroup extends Model {
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function inventories() {
return $this->hasManyDeep(
Inventory::class,
[Category::class, 'category_product', Product::class]
);
}
}

How in laravel to make a deep HasManyThrough?

I created a relationship like this:
Type.City.Street.House.Apartment
In this relation, the apartment must depend on the House and on the Type at the same time, so result sql query must be like this:
select * from `apartments` where `apartments`.`house_id` in ('1', '2', '3') and `type_id` = '777'
The problem is that the HasManyThrough relationship only looks at a two of levels and it's not possible to get to the very first model with it.
Please, advise how this can be done?
My models definations:
class Type extends Model {
public function city() {
return $this->hasMany('App\City');
}
}
class City extends Model {
public function street() {
return $this->hasMany('App\Street');
}
}
class Street extends Model {
public function house() {
return $this->hasMany('App\House');
}
}
class House extends Model {
public function Apartment() {
return $this->hasMany('App\Apartment');
//->where('type_id', '=' type.id) ?????
}
}
class Apartment extends Model {
public $fillable = ['house_id', 'type_id']
}
I would add a mapping for house_id in Apartment model and sets bidirectional mappings among your models
class Apartment extends Model {
public $fillable = ['house_id', 'type_id'];
public function house() {
return $this->belongsTo('App\House', 'house_id');
}
}
class Type extends Model {
public function city() {
return $this->hasMany('App\City');
}
}
class City extends Model {
public function type() {
return $this->belongsTo('App\Type', 'type_id');
}
public function street() {
return $this->hasMany('App\Street');
}
}
class Street extends Model {
public function city() {
return $this->belongsTo('App\City', 'city_id');
}
public function house() {
return $this->hasMany('App\House');
}
}
class House extends Model {
public function street() {
return $this->belongsTo('App\Street', 'street_id');
}
public function Apartment() {
return $this->hasMany('App\Apartment');
//->where('type_id', '=' type.id) ?????
}
}
then you can query apartments as per your criteria like
Apartments::whereHas('house.street.city.type', function ($query) use ($type_id) {
$query->where('id', '=', $type_id);
})
->whereHas('house', function ($query) use ($house_ids) {
$query->whereIn('id', $house_ids);
});
And i guess there is no need for type_id in Apartments model
I created a HasManyThrough relationship with unlimited levels: Repository on GitHub
After the installation, you can use it like this:
class Type extends Model {
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function Apartment() {
return $this->hasManyDeep(Apartment::class, [City::class, Street::class, House::class])
->where('apartments.type_id', $this->id);
}
}
Unfortunately, this doesn't work with eager loading.

Laravel Polymorphic Relation not working

trying to get some polymorphic relations working in laravel 4.
I have a CoreUserAccount table that looks like so:
core_user_account:
id
profile_id
other columns
I then have 2 other tables core_user_client_profile and core_user_consultant_profile. They both have id fields.
i am trying to link them like so:
In the CoreUserAccount model:
public function profile()
{
return $this->morphTo();
}
And in both the other tables i have:
public function user()
{
return $this->morphOne('CoreUserAccount', 'profile');
}
But i don't seem to be able to get any of the profile data through the user object. Any ideas?
Cheers
EDIT
Here is my core_user_account table:
And here are my 2 different profile type tables core_user_client_profile and core_user_consultant_profile:
Here is my model for core_user_account:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class CoreUserAccount
extends Eloquent
implements UserInterface, RemindableInterface
{
protected $table = 'core_user_account';
protected $hidden = array('password');
protected $guarded = array('id', 'password');
public function profileType()
{
return $this->belongsTo('CoreUserProfileType');
}
public function address()
{
return $this->belongsTo('CoreUserAddress', 'user_account_id', 'id');
}
public function profile()
{
return $this->morphTo();
}
public function getAuthIdentifier() {
return $this->getKey();
}
public function getAuthPassword() {
return $this->password;
}
public function getReminderEmail() {
return $this->email;
}
public function getRememberToken() {
return $this->remember_token;
}
public function setRememberToken($value) {
$this->remember_token = $value;
}
public function getRememberTokenName() {
return 'remember_token';
}
}
And my core_user_client_profile model:
class CoreUserClientProfile
extends Eloquent
{
protected $table = 'core_user_client_profile';
public function profileLanguage()
{
return $this->belongsTo('CoreUserProfileLanguages');
}
public function user()
{
return $this->morphOne('CoreUserAccount', 'profile',null,'profile_id',null);
}
}
And my core_user_consultant_profile model:
class CoreUserConsultantProfile
extends Eloquent
{
protected $table = 'core_user_consultant_profile';
public function profileLanguage()
{
return $this->belongsTo('CoreUserProfileLanguages', 'consultant_profile_id', 'id');
}
public function qualifications()
{
return $this->belongsTo('CoreUserConsultantQualifications', 'profile_id', 'id');
}
public function registration()
{
return $this->belongsTo('CoreUserConsultantRegistrations', 'profile_id', 'id');
}
public function specialities()
{
return $this->belongsTo('CoreUserConsultantProfileSpeciality', 'profile_id', 'id');
}
public function user()
{
return $this->morphOne('CoreUserAccount', 'profile');
}
}
I have read the document pointed out in the comments below and understand i seem to have to have a type column in my DB. But what data needs to be stored here? does it automatically get stored or do i have to store it?
Cheers
You should have to have profile_type, and profile_id columns. In profile_type will be stored values: 'CoreUserConsultantProfile' or 'CoreUserClientProfile'. This fields will be populated automaticlly when you save data.
This is example how save data in polymorph relation.
$profile = CoreUserConsultantProfile::find(1);
$account = new CoreUserAccount();
$profile->profile()->save($account);
So now, profile_id=1, and profile_type = 'CoreUserConsultantProfile'

Resources