laravel 与 pluck 不同的价值观

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42447682/
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-09-14 15:24:46  来源:igfitidea点击:

Distinct values with pluck

laraveldistinctlaravelcollectivepluck

提问by Arlind Hajdari

I'm trying to retrieve data from database and bind them to a html select tag, and to bind them i need to use pluck so i get the field i want to show in a array(key => value), because of FORM::select. The normal pluck gets all the results, while i want to use distinct. My model is Room and it looks like:

我正在尝试从数据库中检索数据并将它们绑定到一个 html 选择标记,并绑定它们我需要使用 pluck 所以我得到了我想在数组中显示的字段(键 => 值),因为 FORM: :选择。正常采摘得到所有结果,而我想使用不同的。我的模型是 Room,它看起来像:

    class Room extends Eloquent
{
    public $timestamps = false;

    protected $casts = [
        'price' => 'float',
        'floor' => 'int',
        'size' => 'float'
    ];

    protected $fillable = [
        'capacity',
        'description',
        'price',
        'floor',
        'size',
        'type',
        'photo_name'
    ];
}

While my function I'm using in the controller look like:

虽然我在控制器中使用的功能如下所示:

public function getRooms()
    {
        $roomType = Room::pluck('type','type');
        $roomFloor = Room::pluck('floor','floor');

        return view('roomgrid')->with('type',$roomType)->with('floor',$roomFloor);
    }

And my view contains this piece of code to get floors:

我的观点包含这段代码来获得楼层:

{{FORM::select('floor', $floor, null,['class'=>'basic'])}}

Like this i get duplicated floors, that i don't want. Is there any way so i can get distinct floors and pluck them? Thanks in advance.

像这样,我得到了重复的楼层,这是我不想要的。有什么办法可以让我得到不同的地板并采摘它们吗?提前致谢。

回答by Buglinjo

Why not use groupBy()?

为什么不使用groupBy()

$roomType = Room::groupBy('type')->pluck('type','type');

回答by iateadonut

Room::unique('floor')->pluck('floor', 'floor');

回答by vbarbarosh

distinctcan do the trick:

distinct可以解决问题:

Room::query()->distinct()->pluck('type');

Which will be translated into the following SQL:

这将被翻译成以下 SQL:

SELECT DISTINCT type FROM rooms

回答by Learner

2019 Update

2019年更新

You don't need to use 2 arguments with pluck()

您不需要使用 2 个参数 pluck()

simply do:

简单地做:

$roomType = Room::groupBy('type')->pluck('type');

of course for getting it into array:

当然要将其放入数组:

$roomType = Room::groupBy('type')->pluck('type')->toArray();

Sometimes I use the result for whereInclause, its useful for that.

有时我使用结果 forwhereIn子句,它对此很有用。