Yêu cầu thg 8 20, 2020 2:08 SA 224 2 3
  • 224 2 3
+2

Tại sao từ Eloquent có thể call được function định nghĩa cho query builder?

Chia sẻ
  • 224 2 3

Mọi người cho em hỏi, trong Laravel tại sao mình có thể call được function định nghĩa cho query builder trong eloquent vậy ạ?
Ví dụ như: hàm insert(); của query builder
Mình thể thể gọi được luôn từ Eloquent model như User::insert(); Cảm ơn mọi người.

3 CÂU TRẢ LỜI


Đã trả lời thg 8 20, 2020 3:53 SA
Đã được chấp nhận
+6

Trước đây cũng có một bài viết rất hay về việc sử dụng Magic Methods trong Laravel trên Viblo, trong đó có một phần nhắc đến mối quan hệ giữa Eloquent và Query Builder, bạn có thể xem thêm tại đây để hiểu được rõ bản chất của vấn đề:

https://viblo.asia/p/laravel-and-php-magic-methods-157G5o7ORAje#_eloquent-model-and-query-builder-5

Hiểu đơn giản là Laravel đã sử dụng Magic Methods để có thể giúp gọi các hàm của Query Builder bên trong Eloquent, hay Query Builder thực tế được sử dụng như một tầng ở bên dưới Eloquent, giúp cho Eloquent có thể thao tác đến cơ sở dữ liệu.

Chia sẻ
Đã trả lời thg 8 20, 2020 2:43 SA
+1

Nguồn: https://stackoverflow.com/questions/34530371/laravel-5-model-object-could-call-builder-method-how-does-laravel-do-that

This is because Eloquent usesIlluminate\Database\Query\Builder behind the scenes and you can find all those methods in this Builder class. When you run function that does not exist in Users model in this case, magic method __call(https://www.php.net/manual/en/language.oop5.overloading.php#object.call) is used:

public function __call($method, $parameters)
{
    if (in_array($method, ['increment', 'decrement'])) {
        return call_user_func_array([$this, $method], $parameters);
    }

    $query = $this->newQuery();

    return call_user_func_array([$query, $method], $parameters);
}

as you see in this method newQuery method is executed. And when you look at this method definitions you can see here:

public function newQuery()
{
    $builder = $this->newQueryWithoutScopes();

    foreach ($this->getGlobalScopes() as $identifier => $scope) {
        $builder->withGlobalScope($identifier, $scope);
    }

    return $builder;
}

and further, when you look at newQueryWithoutScopes you'll see there:

$builder = $this->newEloquentBuilder(
        $this->newBaseQueryBuilder()
);

and this newEloquentBuilder method returns new Builder($query); so it's an Illuminate\Database\Query\Builder object

Chia sẻ
Đã trả lời thg 8 20, 2020 2:35 SA
Chia sẻ
Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí