Laravel Eloquent 关系与数据库查询
Laravel Eloquent Relation vs Database Query
我正在做一个 Laravel 项目。我通常通过 Eloquent ORM 获取数据库关系,例如 belongsToMany 或 hasOne 等。但是,当您从这些关系中获取数据时,是否 运行 是一个额外的查询?两者之间是否存在性能差异:
$this->hasOne(Model::class)
和
Model::find($this->some_id)
?非常感谢。
我举个例子。希望对您有所帮助。
我有 2 个模型:
在模型中:
public $fillable = [
'id',
...
];
public function b()
{
return $this->hasOne(B::class, 'a_id', 'id');
}
在 B 模型中:
public $fillable = [
'id',
'a_id',
...
];
public function a()
{
return $this->belongsTo(A::class, 'a_id', 'id');
}
然后你可以得到这样的数据:
$a = A::find($id);
$b = B::find($a->b->id);
echo $a->attributeOfA;
echo $b->attributeOfB;
echo $a->b->attributeOfB;
echo $b->a->attributeOfA;
使用 Laravel Debugbar 或 dd(); 进行测试
我正在做一个 Laravel 项目。我通常通过 Eloquent ORM 获取数据库关系,例如 belongsToMany 或 hasOne 等。但是,当您从这些关系中获取数据时,是否 运行 是一个额外的查询?两者之间是否存在性能差异:
$this->hasOne(Model::class)
和
Model::find($this->some_id)
?非常感谢。
我举个例子。希望对您有所帮助。
我有 2 个模型:
在模型中:
public $fillable = [
'id',
...
];
public function b()
{
return $this->hasOne(B::class, 'a_id', 'id');
}
在 B 模型中:
public $fillable = [
'id',
'a_id',
...
];
public function a()
{
return $this->belongsTo(A::class, 'a_id', 'id');
}
然后你可以得到这样的数据:
$a = A::find($id);
$b = B::find($a->b->id);
echo $a->attributeOfA;
echo $b->attributeOfB;
echo $a->b->attributeOfB;
echo $b->a->attributeOfA;
使用 Laravel Debugbar 或 dd(); 进行测试