Reputation: 820
i have two tables:
**plans:**
planId, plan_name
**Users:**
userId, user_name, password, planId
i tried to get the name of the plan where i select all users.
this is the users model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Users extends Authenticatable {
public $timestamps = false;
protected $table = 'users';
protected $primaryKey = 'userId';
protected $fillable = [
'user_name',
'password',
];
protected $hidden = [
'_token',
];
public function plan()
{
return $this->belongsTo('App\Plans', 'planId');
}
public function validateCredentials( MyUserInterface $user, array $credentials ) {
$plain = $credentials["password"] . $user->getAuthPasswordSalt();
return $this->hasher->check( $plain, $user->getAuthPassword() );
}
}
and this is the plan model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Plans extends Model {
public $timestamps = false;
protected $table = 'plans';
protected $primaryKey = 'planId';
protected $fillable = [
'plan_name'
];
protected $hidden = [
'_token',
];
public function users()
{
return $this->hasMany('App\Users', 'planId');
}
}
when i used: \App\Users::get();
there is no relations in the output... there is only the users.
what can i do?
i tried to used hasOne and the same issue...
tnx a lot
Upvotes: 1
Views: 733
Reputation: 14921
You can eager load the relationships like this:
\App\Users::with('plan')->get();
Or add a $with
property to always eager load it when you fetch an user:
class Users extends Authenticatable
{
protected $with = [
'plan'
];
}
If you don't want to eager load it, you can access the plan of each user's instance like this:
$users = \App\Users::get();
foreach ($users as $user) {
dd($user->plan);
}
Upvotes: 3