Chuyển đến nội dung chính

Eloquent - Query scope & Query relation một lợi thế ngon bổ


Query Scopes và Query Relation , là hai khái niệm không xa lạ với Laravel, có khi developer vẫn làm nó hàng ngày nhưng lại không rõ mình đang sử dụng lợi thế nữa của laravel.


Việc này giảm thiệu việc xử dụng đi xử dụng lại ở những lần query, khi project lớn lên điều này thật tuyệt vời ông mặt trời.

Cụ thể về query scopes, trong model của laravel mình tạo một function với tiền tố "scope" theo sau đó là name theo cammel case.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    /**
     * Scope a query to only include popular users.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }
    /**
     * Scope a query to only include active users.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }
}


Sử dụng scope này bằng cách gọi lại tên đằng sau scope và không cammel case.
$users = App\User::popular()->active()->orderBy('created_at')->get();
Query relation thì sao, thường thì chúng ta vẫn dùng một số khai báo hasMany, belongsTo... đây cũng là một dạng query relation vậy khi có conditional thì sao.Ta có thể dùng cách sau
public function commentsCount()
{
return $this->comments()
->selectRaw('post_id, count(*) as aggregate')
->groupBy('post_id');
}

Sử dụng cũng đơn giản giống như gọi relation

$post = Post::with('commentsCount')->first(); 

Nhận xét

Bài đăng phổ biến từ blog này

Magento2 Cheat Sheet

Magento 2 tutorial http://devdocs.magento.com/guides/v2.1/frontend-dev-guide/bk-frontend-dev-guide.html https://www.creare.co.uk/blog/magento/theming-in-magento-2-part-1 https://www.creare.co.uk/blog/magento/theming-in-magento-2-part-2 http://alanstorm.com/category/magento-2/

Google Chrome cheat sheet - Keyboard shortcuts

Windows and Linux Tab and window shortcuts Shortcut Action Alt+F   or   Alt+E   or F10 Opens the Chrome menu   , which lets you customize and control settings in Google Chrome. Ctrl+Shift+B Toggles the bookmarks bar on and off. Ctrl+H Opens the History page. Ctrl+J Opens the Downloads page. Shift+Esc Opens the Task Manager. Shift+Alt+T Sets focus on the first tool in the browser toolbar. You can then use the following shortcuts to move around in the toolbar: ·          Press   Tab, Shift+Tab, Home, End, right arrow,   and   left arrow   to move focus to different items in the toolbar. ·          Press   Space   or   Enter   to activate toolbar buttons, including page actions and browser actions. ·     ...

Magento 2 Bookmark Events

Tổng hợp events có trong magento ,  tạo thêm event bao nhiêu tuỳ thích theo link sau Events and observers