【问题标题】:Add a new column with a value to the select query in Laravel在 Laravel 的选择查询中添加一个带有值的新列
【发布时间】:2017-06-15 12:41:41
【问题描述】:

我想知道如何在 Laravel 中进行选择连接时创建一个名为“type”的默认变量并将值设置为“car”。

到目前为止,这是我的代码:

$items = DB::table('items')->orderBy('created_at', 'desc')
                           ->join('items_categories', 'items.item_category_id', '=', 'items_categories.category_id')
                           ->select( 
                                     'items.id as items___item_id',
                                     'items.item_title as items___item_title',
                                     'items_categories.id as items_categories___category_id',
                                     'items_categories.title as items_categories___category_title',
                                   )
                           ->take(20);

这很好用。但是,我需要为此选择的每条记录获取/添加自定义键和值,以便稍后在模板中使用它来进一步过滤内容。

所以,我需要添加一个名为type 的键,其值为car,所以在 print_r 中我会看到每条记录的 type => car,我可以在我的代码中使用它。

怎么做?

我可以把那个 somhow 放在选择中吗?

喜欢:

->select( 
           'items.id as items___item_id',
           'items.item_title as items___item_title',
           'items_categories.id as items_categories___category_id',
           'items_categories.title as items_categories___category_title',
           //something like this?
           'type' = 'car'
        )

因为现在我得到了这个:

Array
(
    [0] => stdClass Object
        (
            [items___item_id] => 10
            [items___item_user_id] => 2
            [items___item_title] => A new blue truck
            [items_categories___category_id] => 1
            [items_categories___category_title] => Truck
        )

    [1] => stdClass Object
        (
            [items___item_id] => 11
            [items___item_user_id] => 2
            [items___item_title] => VW Tiguan
            [items_categories___category_id] => 1
            [items_categories___category_title] => SUV
        )

我想得到这个:

Array
(
    [0] => stdClass Object
        (
            [items___item_id] => 10
            [items___item_user_id] => 2
            [items___item_title] => A new blue truck
            [items_categories___category_id] => 1
            [items_categories___category_title] => Truck
            [type] => car
        )

    [1] => stdClass Object
        (
            [items___item_id] => 11
            [items___item_user_id] => 2
            [items___item_title] => VW Tiguan
            [items_categories___category_id] => 1
            [items_categories___category_title] => SUV
            [type] => car
        )

如果可能,不在模型文件中,而是在一次查询期间,因为我需要进行此修改的只有一次。

【问题讨论】:

  • 有人知道怎么做吗?
  • 你不使用 Eloquent 有什么原因吗?
  • 您是否要根据类型进行选择,例如car?
  • @RikardOlsson 我想在 select 语句期间动态创建一个名为 type 的新虚拟列(数据库中不存在此列),并将该字段中的所有值分配给 @987654329 @(所有结果)。
  • 我不确定我是否遵循.. 在您的查询结果中,您想动态添加一个带有值的新“列”,然后将此结果分配给您称为 Car 的模型?

标签: php mysql laravel select eloquent


【解决方案1】:

你可以使用这个方法:

$data = DB::table('items')
   ->Select('items.id as items___item_id',
            'items.item_title as items___item_title');

# Add fake column you want by this command
$data = $data->addSelect(DB::raw("'fakeValue' as fakeColumn"));

$data = $data->orderBy('items.id')->get();

尽情享受吧!

【讨论】:

    【解决方案2】:

    您将希望为您的 items 表创建一个模型并以这种方式查询它。使用 eloquent,您可以通过将列名称添加到 $appends 属性然后定义模型属性来动态创建列。

    php artisan make:model Item
    

    任何模型都会自动查找模型名称的复数形式的表(Item 查找“items”)。在 Item 模型中,添加以下行

    /**
     * Append custom columns to the model
     * 
     * @var array
     */
    protected $appends = ['type'];
    
    /**
     * Define the type column to every Item object instance
     * 
     * @return string
     */
    public function getTypeAttribute()
    {
        return 'car';
    }
    

    现在更新您的查询以使用模型而不是 DB::select。确保使用控制器顶部的模型

    use App\Item; 
    
    ....
    
    $items = Item::orderBy('created_at', 'desc')
                           ->join('items_categories', 'items.item_category_id', '=', 'items_categories.category_id')
                           ->select( 
                                     'items.id as items___item_id',
                                     'items.item_title as items___item_title',
                                     'items_categories.id as items_categories___category_id',
                                     'items_categories.title as items_categories___category_title',
                                   )
                           ->take(20)->get();
    

    在使用模型时,您需要添加 get() 作为最终方法,以便它返回集合与 DB::select。

    【讨论】:

    • 谢谢,没有模型部分有机会实现吗?我的意思是我有一个模型项目,但我只需要在一种情况下做这个特定的事情,所以,这将是一个矫枉过正。
    • 您提到添加 'type' = 'car' 的那一行应该可以正常工作,但模型确实是最好的方法。您已经在使用 Eloquent 并且只是将 DB::select 替换为模型调用。如果它有效且干净,没有什么是矫枉过正的!
    • 嗯,如果我尝试'type' = 'car',我会收到syntax error, unexpected '=' ,如果我尝试'type = car',我会收到Column not found: 1054 Unknown column 'type = car'
    • 我不确定内联的确切语法,但您提到的内容是正确的。或者您可以添加模型文件和我提到的 2 种方法并完成它!我有你的解决方案,但由于某种原因你仍然不满意
    • 我需要知道如何在当前语句中进行操作。我现在遇到语法错误。
    【解决方案3】:

    这是这个问题的解决方案,希望它在未来对其他人有所帮助。

    $items = DB::table('items')->orderBy('created_at', 'desc')
                               ->join('items_categories', 'items.item_category_id', '=', 'items_categories.category_id')
                               ->select(DB::raw('"car" AS type, 
                                                 items.id as items___item_id,
                                                 items.item_title as items___item_title,
                                                 items_categories.id as items_categories___category_id,
                                                 items_categories.title as items_categories___category_title
                                                ')
                                       )
                               ->take(20);
    

    【讨论】:

    • 您不需要将所有选择放入DB::raw(),将DB::raw('"car" AS type') 放入原始查询中就足够了。
    【解决方案4】:

    我像这个示例一样实现它

        $first = Message::where('from_id', '=', Auth::user()->id)
            ->where('to_id', '=', $id)->get();
        foreach ($first as $f)
            $f->is_sent = true;
    
        $second = Message::where('from_id', '=', $id)
            ->where('to_id', '=', Auth::user()->id)->get();
        foreach ($second as $s)
            $s->is_sent = false;
    
        $chats = $first->merge($second)
            ->sortBy('created_at');
    
        return $chats->toJson();
    

    你可以通过 for eachafter get() 方法来做到这一点

    【讨论】:

      【解决方案5】:

      我遇到了同样的要求,我知道它已经晚了,但它可能会在未来帮助某人:

      这是我如何在 Laravel eloquent 模型中添加自定义字段的代码

      $searchResults = Blog::with('categories')
                      ->where('title', 'like', "%{$keyword}%")
                      ->orWhere('description', 'like', "%{$keyword}%")
                      ->select(['*', DB::raw("'{$keyword}' as keyword")])
                      ->get();
      

      谢谢

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-01
        • 1970-01-01
        • 2017-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多