23

我有一个查询来从租用表中选择所有行并以随机顺序显示它们。

DB::table('hire_bikes')->order_by(\DB::raw('RAND()'))->get();

我现在希望能够放

concat(SUBSTRING_INDEX(description, " ",25), "...") AS description

进入查询的 SELECT 部分,这样我就可以select *从表中得到一个缩短的描述。

我知道这可以通过运行原始查询来实现,但我希望能够使用 Fluent 或至少部分 Fluent(如上)来做到这一点。

我该怎么做?

4

3 回答 3

38

您实际上可以使用 selectAS而不使用DB::raw(). 只需将数组传入select()方法中,如下所示:

$event = Events::select(['name AS title', 'description AS content'])->first();

// Or just pass multiple parameters

$event = Events::select('name AS title', 'description AS Content');

$event->title;
$event->content;

我测试了它。

另外,我建议不要使用DB:raw()查询来连接您的描述字段。如果您使用的是 eloquent 模型,您可以使用访问器和修改器为您执行此操作,因此如果您需要有限的描述,您可以简单地将其输出到您的视图中,而不必每次都使用相同的查询来获得有限的描述。例如:

class Book extends Eloquent
{
    public function getLimitedDescriptionAttribute()
    {
        return str_limit($this->attributes['description'], $limit = 100, $end = '...');
    }
}

在您看来:

@foreach($books as $book)

    {{ $book->limited_description }}

@endforeach

示例输出(不准确限制):

The description of this book is...

我还建议不要使用 DB 外观,因为它总是使用您的默认连接。如果您正在查询辅助连接,除非您使用以下方式主动指定它,否则它不会考虑到这一点:

DB::connection('secondary')->table('hire_bikes')->select(['name as title'])->get();

请注意,如果您使用 select AS ( name AS title) 并且希望更新您的模型,您仍然必须设置与您的数据库列一致的正确属性名称。

例如,这将导致异常,因为该title列在您的数据库表中不存在:

$event = Events::select('name AS title')->first();

$event->title = 'New name';

$event->save(); // Generates exception, 'title' column does not exist.
于 2014-09-08T14:13:32.290 回答
23

您可以通过将 a 添加DB::raw()到流利查询中的选择数组来执行此操作。我在本地对此进行了测试,效果很好。

DB::table('hire_bikes')
  ->select(
      array(
        'title',
        'url',
        'image',
        DB::raw('concat(SUBSTRING_INDEX(description, " ",25),"...") AS description'),
        'category'
      )
    )
  ->order_by(\DB::raw('RAND()'))
  ->get();
于 2013-01-24T13:11:19.467 回答
0
select(array(DB::raw('latitude as lat'), DB::raw('longitude as lon')))
于 2014-09-03T09:53:41.530 回答