Tuesday, 20 April 2021

Laravel first() && entity relationships && Laravel how to use With()

Laravel first()

https://laravel.com/docs/5.7/eloquent-serialization#serializing-models-and-collections

$user = App\User::with('roles')->first();


return $user->toArray();


Laravel  entity relationships

https://laravel.com/docs/5.7/eloquent-relationships#one-to-one

<?php


namespace App;


use Illuminate\Database\Eloquent\Model;


class User extends Model

{

    /**

     * Get the phone record associated with the user.

     */

    public function phone()

    {

        return $this->hasOne('App\Phone');

    }

}

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');

Laravel how to use With()

https://stackoverflow.com/questions/26005994/laravel-with-method-versus-load-method

NOTE :
This must be performed in users.php first
App\users.php 
public function comment() {
return $this->hasOne('App\comments
', 'user_id', 'id');
}
Then Larave Eloquent :: with can be performed, it is acting like innerJoin(join) from users join commnets 
on users.id = comments.user_id, see below :
$users = User::with('comments')->get(); 

...if we have 5 users, the following two queries get run immediately:

select * from `users`
select * from `comments` where `comments`.`user_id` in (1, 2, 3, 4, 5)
https://stackoverflow.com/questions/57498767/whats-the-with-method-in-laravel

 Let's give you direct example. If you've user table and that user related multiple tables right?? and it belongs with multiple table as well?

Here, I take Four tables.

city

  1. id
  2. name

User

  1. id
  2. name
  3. city_id

user_profile

  1. id
  2. user_id
  3. address
  4. phone

user_documents

  1. id
  2. user_id
  3. document_name
  4. type

User belongsTo one city,

User has one profile

User has many documents.

Now In User model you'll define the relationship with every table.

User.php

//User belongs To Country
public function city(){
    return $this->belongsTo('App\City','city_id','id')->withDefault();
}


//User hasone profile
public function profile(){
    return $this->hasOne('App\Profile','user_id','id')->withDefault();
}

//User hasmany document
public function documents(){
    return $this->hasMany('App\UserDocument','user_id','id')->withDefault();
}

Now if you want to access this all data in controller then you can get by using with()

Controller

App\User::with('country','profile','documents')->get();

you'll get all data in object as


User

id

name

  • {city data}

  • {profile}

  • {documents}


In addition, You can get multiple model nested relationship as well, Like city belongs to state and if you want to get state data with city then,

User::with('city.state','profile','documents')->get(): 
//define state relationship in city model you'll get state data with city as well.

You can also add condition in with()

User::with(['document'=>function ($q){
    $q->where('type','pdf');
}]);





No comments:

Post a Comment