LoginSignup
0
1

More than 5 years have passed since last update.

Laravel Join scopeOfComputer

Last updated at Posted at 2017-08-25

laravel の Modelでjoinの使い方

Computerテーブルは post_id と server_id持っている。
例1.

    public function scopeOfComputer($query, $computerId)
    {
        return $query
            ->join('post_servers', 'post.id', '=', 'post_id')
            ->join('servers', 'server_id', '=', 'servers.id')
            ->where('servers.computer_id', $computerId);
    }

例2.

 public function scopeWatchersOf($query, Topic $topic)
    {
// function ($join) use ($topic) メソードの中の関数に受け取ったを引数を渡す
        return $query->join('watches', function ($join) use ($topic) {
            $join->on('watches.topic_id', '=', 'topics.id')
                ->where('watches.topic_id', '=', $topic->id);
        })
            ->join('users', 'users.id', '=', 'watches.user_id')
            ->select(['users.id', 'users.name', 'users.avatar']);
    }

hasManyThroughの使い方

class Country extends Model
{
    public function posts()
    {
        return $this->hasManyThrough('App\Post', 'App\User','country_id', 'user_id', 'id');
    }
}

リレーションのキーをカスタマイズしたい場合は、hasManyThroughメソッドの第3引数と、第4引数を指定してください。第3引数は仲介モデルの外部キー名、第4引数は最終的なモデルの外部キー名です。そして第5引数はローカルキーです。

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