Laravel 4 フレームワークを使用して PHP アプリケーションを開発しています。ユーザーとロールモデルをセットアップしました。役割は多くのユーザーに属することができ、ユーザーは多くの役割を持つことができます。役割のないユーザーを選択したいと思います。LaravelのORMを使用してこのクエリを実行するには?
ここに私の Role.php があります
class Role extends Eloquent {
protected $table = 'roles';
public function users() {
return $this->belongsToMany('User', 'user_roles');
}
}
私の User.php には、次のコードがあります。
public function roles() {
return $this->belongsToMany('Role', 'user_roles');
}
以下のコードを試しましたが、ロールなしでユーザーを作成してもユーザーが返されません。
User::has('roles', '=', 0)->paginate(15);
以下のコードは機能しますが、ユーザーは stdClass オブジェクトです。それらをユーザーオブジェクトにする必要があります。
$users = DB::table('users')->whereNotIn('id', function($query){
$query->select('user_id')->from('user_roles');
})->paginate(15);
編集
User::has('roles', '=', 0)->paginate(15) のクエリログを追加
array(3) { ["query"]=> string(189) "select * from "users" where (select count(*) from "roles" inner join "user_roles" on "roles"."id" = "user_roles "."role_id" where "user_roles"."user_id" = "users"."id") = ? limit 15 offset 0" ["bindings"]=> array(1) { [0]=> int(0) } ["時間"]=> float(0.11) }