简体   繁体   中英

Laravel Eloquent Relation vs Database Query

I'm working on a Laravel project. I usually get database relations through Eloquent ORM, like belongsToMany or hasOne and such. But when you get data from these kind of relations, does it run an extra query? Is there a performance difference between:

$this->hasOne(Model::class)

and

Model::find($this->some_id)

? Thank you very much.

I will give you some example. I hope this can help you.

I have 2 models:

In A model:

  public $fillable = [
        'id',
        ...
    ];
public function b()
    {
        return $this->hasOne(B::class, 'a_id', 'id');
    }

In B model:

  public $fillable = [
        'id',
        'a_id',
        ...
    ];
public function a()
    {
        return $this->belongsTo(A::class, 'a_id', 'id');
    }

Then you can get data like that:

$a = A::find($id);
$b = B::find($a->b->id);
echo $a->attributeOfA;
echo $b->attributeOfB;
echo $a->b->attributeOfB;
echo $b->a->attributeOfA;

use Laravel Debugbar or dd(); to test it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM