【问题标题】:Getting specific columns from Laravel Eloquent从 Laravel Eloquent 获取特定列
【发布时间】:2015-02-10 22:49:49
【问题描述】:

我一直在为此自责,似乎无法让我的 JSON 只显示房间的标题和描述(如果它们是实时的)。我试过使用return $this->hasMany('Room')->select(array('id', 'title', 'description'));,但它根本没有返回房间。

有人可以帮忙吗?我确信这一定很容易实现,因为我理解 Laravel Eloquent 对这类任务很简单。

JSON

[
    {
        id: 1,
        building_title: "Drum Castle"
        room: [
            {
                id: 1,
                building_id: 7,
                title: "Snooker Room",
                description: "Full Description",
                live: 1
            }
        ]
    }
]

建筑模型

public function room()
{
    return $this->hasMany('Room');
}

房间模型

public function building()
{
   return $this->belongsTo('Building', 'building_id');
}

控制器

$buildings = Building::with('room')->get();

【问题讨论】:

  • Building::with('room')->get(); 的输出是什么?
  • 上面的 JSON 是我得到的一个例子。

标签: laravel laravel-4


【解决方案1】:

由于您没有选择building_id 字段,您尝试限制关系中的字段失败。如果你没有得到这个字段,Laravel 不知道哪些房间属于哪些建筑物(想想急切加载的关系)。

一种实现您想要的方法是在建筑物或房间上覆盖toArray() 方法(由toJson() 调用)。

另一个选项是在 Room 模型上设置隐藏/可见属性。属性将控制在转换为数组时哪些字段是隐藏/可见的。

class Room extends Eloquent {
    protected $hidden = array('building_id', 'live');
    // or
    protected $visible = array('id', 'title', 'description');

    // rest of class
}

【讨论】:

  • 效果很好。我没有考虑过使用隐藏。谢谢
猜你喜欢
  • 2020-07-09
  • 2020-06-02
  • 2013-11-20
  • 1970-01-01
  • 2014-08-06
  • 2022-01-11
  • 2019-04-01
  • 1970-01-01
相关资源
最近更新 更多