php - Default User model and Relatinship - Laravel 5.4 -
i use default user model , have created userstatus model:
user
class user extends authenticatable { use notifiable; /** * attributes mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * attributes should hidden arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function status() { return $this->belongsto('app\userstatus'); }
}
userstatus
namespace app; use illuminate\database\eloquent\model; class userstatus extends model { public $timestamps = false; public function users() { return $this->hasmany('app\user'); } }
i cant access related model attribute because $user->status null:
$users = user::all(); foreach ($users $user) { var_dump($user->status->name); }
what best practice/solution?
thanks!
your query cause n+1 query problem.
try efficient
$users = user::with('status')->get(); foreach ($users $user) { logger($user->status->name); }
Comments
Post a Comment