First, In my mysql database, I have 2 tables named "users" and "users_details" and they are in relationship
users table
id (PK, AI, INT), username (VARCHAR, UNQ), password (VARCHAR), fullname (VARCHAR)
and the users_table
id (PK, AI, INT), email (VARCHAR), phone (VARCHAR), address (VARCHAR), has_record (VARCHAR), user_id (int, FK = reference table 'users.id')
and my model bindings.
'User' model
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['username', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public function user_details(){
return $this->hasOne('App\users_details');
}
}
and the 'users_details' model
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class users_details extends Model {
protected $table = "user_details";
public function ud()
{
return $this->belongsTo('App\User');
}
}
and I know I can just do like
$data = User::find(1)->with('user_details'); //or
$data = User::find(1)->user_details;
but how about I want to get the fullname record from the 'User' table which is the main reference table for the 'users_table' 'user_id' foreign key? how to do it? I tried
$data = users_details::where('has_record', '=', 'no')->with('ud')->get(); //get all the records where column 'has_record' of 'users_details' is equal to 'no'
$data = $data->ud->fullname; //get the fullname
but unfortunately and sadly not working, any help, ideas, clues, suggestions, recommendations please?
UPDATE:
I achieved it using Query builder
$test = DB::table('users')
->join('user_details', 'users.id', '=', 'user_details.user_id')
->where('has_record', '=', 'no')
->get();
but is there a way I could do it using the power of Eloquent?
You can just do like that.
According to your code
Find one user detail with user eager load and get name.
$user_detail = user_details::with('ud')->find(1);
$user_detail->ud->name;
Get all user detail with user eager load and get user name.
$user_details = user_details::with('ud')->get();
foreach($user_details as $user_detail){
echo $user_detail->user->name;
}
I have a suggestion for you if you want. Try to follow the singular/plural format which can make the code more readable.
// User Classs.
public function user_detail(){
return $this->hasOne('App\UserDetail');
}
// UserDetail Class.
public function user(){
return $this->belongsTo('App\User');
}