8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Laravel5.1】 Eloquent の with() の selectについて

Last updated at Posted at 2015-12-29

Eloquent の with で取得するカラムを指定したかったのですが、けっこーハマっので残します。

HogeDataGroupModel
    // 項目
    protected $fillable = [
            'name',
            'group_type',
            'order'
        ];

    // 関連
    public function hogeDatas()
    {
        return $this->hasMany('App\Models\HogeDataModel');
    }
HogeDataModel
    // 項目
    protected $fillable = [
            'hoge_data_id',
            'value',
            'start_at',
            'end_at'
        ];

    // 関連
    public function hogeDataGroup()
    {
        return $this->belongsTo('Models\HogeDataGroupModel');
    }

上記のように、
HogeDataGroup : HogeData = 1 : 多
のケースで考えると、
HogeDataModel の value のみを 抽出する場合、valueだけでなく、FKも必要です。←これにハマった。

HogeController
    HogeDataGroupModel::where('group_type', 1)
       ->with(['hogeDatas' => function ($q) {
           $q->select('value', 'hoge_data_id'); // ← hoge_data_id が必要。
       }])
8
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?