0
0

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 1 year has passed since last update.

belongsToManyで取得したデータからpivotテーブルの情報を除く

Last updated at Posted at 2023-02-23

やりたいこと

多対多の関係性のテーブルからリレーション先のデータを取得するとpivotテーブルの情報も含まれてしまうから、それを除外した上で取得したい。

以下のようなUserとGroupのmodelがあります。

User.php
class User extends Authenticatable
{
    public function groups()
    {
        return $this->belongsToMany(Group::class);
    }
}
Group.php
class Group extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}

GroupからUserの情報を取得しようとすると、、

GroupController.php
$group = Group::find(1);
$group->users()->get(['users.id', 'name'])

pivotテーブルの情報も含まれていて、これを削除したい。

group: [
{
    id: 3,
    name: "テスト太郎",
    pivot: {
        user_id: 3,
        group_id: 1
    }
},

対応方法

方法は二つあります。

1.リレーション先のモデルにhiddenプロパティを追加する

User.php
class User extends Authenticatable
{
    protected $hidden = [
        'pivot',//追加する
    ];

    public function groups()
    {
        return $this->belongsToMany(Group::class);
    }
}

2.取得時にmakeHidden()を使用する

GroupController.php
$group = Group::find(1);
$group->users()->get(['users.id', 'name'])->makeHidden('pivot');

参考:https://readouble.com/laravel/8.x/ja/eloquent-collections.html#method-makeHidden

以上

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?