php 向 Laravel 中的选择查询添加一个带有值的新列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41934528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:30:55  来源:igfitidea点击:

Add a new column with a value to the select query in Laravel

phpmysqllaravelselecteloquent

提问by John Doeherskij

I would like to know how to create a default variable called "type" and set a value to "car" while doing a select join in Laravel.

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

Here is my code so far:

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

$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);

This works nice. However, I need to get/add a custom key and value for each record of this select so I can use it later in the template to filter stuff further.

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

So, I need to add a key called typewith a value of carso in the print_r I will see type => car for every record and I can use this in my code.

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

How to do that?

怎么做?

Can I put that somhow in the select?

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

Like:

喜欢:

->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'
        )

Because right now I am getting this:

因为现在我得到了这个:

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
        )

And I want to get this:

我想得到这个:

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
        )

If possible, not in the model file, but during the one query, because it's only one time when I need this modification to be done.

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

回答by W. Dan

You can use this method:

您可以使用此方法:

$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();

Enjoy it!

好好享受!

回答by Rob Fonseca

You will want to create a model for your items table and query it that way. Using eloquent, you can create columns on the fly by adding column names to the $appends property and then defining a model attribute.

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

php artisan make:model Item

Any model automatically looks for a table that is the plural of the model name (Item looks for 'items'). In the Item model, add the following lines

任何模型都会自动查找作为模型名称复数形式的表(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';
}

Now update your query to use the model instead of DB::select. Make sure to use the model at the top of your controller

现在更新您的查询以使用模型而不是 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();

You need to add get() as the final method when using a Model for it to return a collection vs. DB::select.

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

回答by John Doeherskij

Here is the solution for this problem, hope it helps somebody else in the future.

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

$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);

回答by saber tabatabaee yazdi

i implement it sth like this sample

我像这个示例一样实现它

    $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();

you can do it by for eachafter get() method

你可以通过 for eachafter get() 方法来完成