9
9

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 5 years have passed since last update.

Laravel Eloquentのjoin結合先は論理削除に留意する

Last updated at Posted at 2015-07-31

LaravelのSoftDeletingTraitは非常に便利なのですが、
適用範囲はQueryBuilderを発行する基となるクラスです。

つまり、join/leftJoin/rightJoinで結合した先の論理削除条件は
自動ではセットされません。

そこで、例えばこんな感じになります。

Product::where('products.type_id', 1)
    ->leftJoin('options', function ($join) {
        $join->on('products.id', '=', 'options.product_id')
            ->whereNull('options.deleted_at');
    })
    ->select('products.name as product_name', 'options.name as option_name')
    ->get();

基本的にはeager loadingすれば良いと思うのですが、
joinする場合は気を付けた方が良いですね。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?