简体   繁体   English

如何从 Laravel 中的 Posts::all() 获取标题?

[英]How to get title of from Posts::all() in Laravel?

I am trying to get attribute title from all of the Posts.我正在尝试从所有帖子中获取属性title Right now I have, Posts::all()现在我有, Posts::all()

I have tried, Posts::title and Posts::title->all()我试过了, Posts::title 和 Posts::title->all()

Use pluck :使用采摘

$titles = Posts::all()->pluck('title');

Since each Eloquent model serves as a query builder , you may use any query builder method avaible.由于每个 Eloquent model 都用作查询构建器,因此您可以使用任何可用的查询构建器方法。

So instead of getting all the attributes of the model with all() method, and then filtering the resulting collection, you can directly do the query to get only that attribute.因此,无需使用all()方法获取 model 的所有属性,然后过滤结果集合,您可以直接执行查询以仅获取该属性。

Retrieving Results检索结果

Retrieving A List Of Column Values检索列值列表

If you would like to retrieve a Collection containing the values of a single column, you may use the pluck method.如果您想检索包含单个列的值的集合,您可以使用 pluck 方法。 In this example, we'll retrieve a Collection of post titles:在此示例中,我们将检索帖子标题的集合:

$titles =  Posts::pluck('title');

foreach ($titles as $title) {
    echo $title;
}

Or with select:或使用 select:

Selects选择

Specifying A Select Clause指定 Select 子句

You may not always want to select all columns from a database table.您可能并不总是希望 select 数据库表中的所有列。 Using the select method, you can specify a custom select clause for the query:使用 select 方法,您可以为查询指定自定义 select 子句:

$posts = Posts::select('title')->get();

foreach ($posts as $post) {
    echo $post->title;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM