Php 确定Laravel查询中是否存在关系
我在工作中继承了一个Laravel5项目,我想知道如何检查相关模型的存在,以避免出现空异常 区块日期模型Php 确定Laravel查询中是否存在关系,php,laravel,eloquent,Php,Laravel,Eloquent,我在工作中继承了一个Laravel5项目,我想知道如何检查相关模型的存在,以避免出现空异常 区块日期模型 class BlockDate extends Model { public function claims() { return $this->belongsToMany(User::class); } } class User extends Model { public function blocks() {
class BlockDate extends Model {
public function claims()
{
return $this->belongsToMany(User::class);
}
}
class User extends Model {
public function blocks()
{
return $this->belongsToMany(BlockDate::class);
}
}
用户模型
class BlockDate extends Model {
public function claims()
{
return $this->belongsToMany(User::class);
}
}
class User extends Model {
public function blocks()
{
return $this->belongsToMany(BlockDate::class);
}
}
数据透视表
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger(block_date_id');
$table->foreign('block_date_id')->references('id')->on(block_dates);
用户可以为假期请求申请一系列日期。但是,用户可能没有声明或日期可能没有声明。我目前正在使用
if ($user->blocks->count() > 0) {
$dates = $user->blocks->sortByDesc('created_at');
// more logic here....
}
我不喜欢在任何地方使用count,有没有一种方法可以合并支票,如:
// I don't know what hasClaimedDates might be
$dates = $user->hasClaimedDates()->blocks->sortByDesc('created_at');
Laravel提供了一种防止空值的辅助方法:
// will return either a collection or null
$dates = optional($user->blocks)->sortByDesc('created_at');
您可以使用实际关系方法,而不是魔法访问器:
$sortedDates = $user->blocks()->latest()->get();
如果没有建立关系,这将为您提供一个空集合,但排序不会失败
注意:latest()
在本例中相当于orderBy('created_at','desc')
顺便说一下,如果您使用
$user->blocks->count()
,它将首先将所有相关模型加载到内存中,然后对关系进行计数。如果以后你打算使用相关的模型,那就好了。但如果你不这样做,你只计算它们,这是浪费资源。在这种情况下,$user->blocks()->count()
执行的数据库查询只返回一个数字,因此性能更高。特别是当你有很多相关的模型时,要考虑到这一点