我想知道为什么当数据库表中不存在请求的记录时,我的Models返回null,而不是返回空集合或空Model实例。
这是我的型号
class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $softDelete = true;
protected $fillable = [
'id',
'email',
'password',
'first_name',
'last_name',
'state_id'
];
public function state()
{
return $this->belongsTo('App'Models'State','state_id','id');
}
}
class State extends Model
{
protected $fillable = [
'name',
'country_id',
'active'];
}
状态表
id name country_id active
1 texas 1 1
2 alaska 1 1
用户表
id first_name state_id
1 frank null
问题来了,还是这就是它的行为方式?
$user = User::with('state')->get(); //returns null
$user->state->name; //surely throws an exception
//I don't want to do this or MUST I?:
if (is_object($user))
$state = $user->state->name;
当状态表中不存在用户的state_id
时,我希望Laravel返回一个空集合,而返回null,
我遇到的问题是,我使用的Transformer需要state model
的实例,而不是空
public function includeState(User $model)
{
$state = $model->state; //null is being returned here
return $this->item($state, new StateTransformer); //this throws an exception when it receives null
}
请参阅:http://fractal.thephpleague.com/
您总是可以这样做:
if(!$state = $model->state) {
$state = new State();
}
或者,这可能工作
$state = ($model->state != null ? $model->state : new State());
如果您只得到一个用户,则不需要急于加载with()
。
只需:
$user = User::find($id);
$user->state->name
当你执行$user = User::with('state')->get();
时,你会得到一个ALL用户的集合。所以$user->state
不起作用。
Laravel有时会返回null $user = User::with('state')->get();
,因为在使用belongsTo时不需要指定密钥,除非与id不同。因此来自:
public function state()
{
return $this->belongsTo('App'Models'State','state_id','id');
}
收件人:
public function state()
{
return $this->belongsTo('App'Models'State');
}
这应该奏效。
您需要在用户之间循环以获得每个用户的状态。