Home >PHP Framework >Laravel >Introducing the usage of Laravel subquery statements

Introducing the usage of Laravel subquery statements

藏色散人
藏色散人forward
2021-01-28 16:59:156137browse

The following tutorial column will introduce you to the usage of Laravel subquery statements. I hope it will be helpful to friends who need it!

class UserController extends Controller{
    public function index()
    {
        $columns = ['id', 'name', 'email', 'created_at'];
        $users = User::addSelect([
            'last_post_title' => Post::select(['title'])
                ->whereColumn('user_id', 'users.id')
                ->where('status', Post::STATUS_NORMAL)
                ->orderByDesc('created_at')
                ->limit(1)
        ])->orderByDesc('id')->paginate(20, $columns);
        return view('user.index', ['users' => $users]);
    }}
The addSelect method can be used to add a query field to an existing query instance. We pass an array - the array key is the returned query field name, that is, the SQL statement In last_post_title, the array value is the corresponding subquery logic. Note that the foreign key association needs to be set through the whereColumn method. Others are the same as normal Eloquent queries.

The above is the detailed content of Introducing the usage of Laravel subquery statements. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete