我使用默认的用户模型,我创建了一个 UserStatus 模型:
用户
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for 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');
}
}
我无法访问相关的模型属性,因为 $ user-> status 为NULL:
$users = User::all();
foreach ($users as $user) {
var_dump($user->status->name);
}
最佳做法/解决方案是什么?
谢谢!
答案 0 :(得分:0)
您的查询将导致N + 1查询问题。
尝试这是有效的
$users = User::with('status')->get();
foreach ($users as $user) {
logger($user->status->name);
}
答案 1 :(得分:0)
有两种方法可以解决:
只需添加防御条件:
user_status_id
您可以在users表中将可为空的列定义为User
,并将其作为user_status表中id的外键,并在$users = User::whereNotNull('user_status_id')->get();
模型中创建关系:hasOne并提供外键和那么只有那些具有某种状态的用户才会被淘汰:
{{1}}