Get the specified column of a database using Laravel's eloquent model

Source: Internet
Author: User

When using Laravel's orm--eloquent, one of the most frequently encountered operations is to take some of the properties in the model, and the corresponding is to fetch a specific column of the table in the database.

If you use the DB façade to write query constructors, you only need to call the Select () method chained:

$users = db::table (' users ')->select (' name ', ' email as User_email ')->get ();

There are two ways of using eloquent:

1. Use SELECT ()

$users = user::select ([' name '])->get ();

2. Pass the column an array group as a parameter directly into all ()/get ()/find (), etc.

1 $users = User::all ([' name ']); 2 $admin _users = user::where (' role ', ' admin ')->get ([' id ', ' name ']); 3 $user = User::find ($user _id, [' name ']);

Use the same in an associative query:

$posts = User::find ($user _id)->posts ()->select ([' title '])->get ();
$posts = User::find ($user _id)->posts ()->get ([' title ', ' description ']);

Note that you cannot use dynamic properties (->posts) to invoke an affinity relationship, but you need to use an association relationship method (->posts ()).

Use Laravel's eloquent model to get the specified columns of the database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.