【问题标题】:Laravel returning only single columnLaravel 只返回单列
【发布时间】:2016-05-09 20:19:09
【问题描述】:

在我的数据库中,我有类别和大小,它们有一个表将它们匹配在一起,称为 category_sizes,如下所示:

我想得到一个包含所有size_id 的数组,其中category_id = 4 所以我做到了:

$catSizes = CategorySize::where('category_id', 4)->value('size_id');
return($catSizes);

但它只返回一个结果。如何获得一个包含所有 size_id 的数组,以便稍后在 where_in 语句中使用它。

我也尝试过采摘,但这也只给出了一行。

$catSizes = CategorySize::where('category_id', 4)->pluck('size_id');
dd($catSizes);

我的 CategoySize 模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class CategorySize extends Model
{
    protected $table = 'category_sizes';
}

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    试试这个:

    DB::table('category_sizes')->where('category_id', 4)->get('size_id');
    

    或者:

    DB::table('category_sizes')->select('size_id')->where('category_id', 4)->get();
    

    【讨论】:

    • 只是为了我的兴趣:你建议DB::table而不是使用模型有什么原因吗?
    • @Peh,我想这里也可以使用 Eloquent(-&gt;pivot 和 -&gt;withPivot 方法):laravel.com/docs/5.1/eloquent-relationships#many-to-many - 但我无法在没有测试的情况下发布有效的 Eloquent 代码(我没有'现在没有足够的时间,抱歉)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 2016-11-27
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多