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

Introducing the usage of Laravel subquery statements

藏色散人
Release: 2021-02-01 09:15:15
forward
6106 people have browsed it

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]);
    }}
Copy after login
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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template