2

次のような 2 つのテーブルがあるとします。

users:
    - id
    - username

profiles:
    - user_id
    - name

datamapper ORM codeigniter を使用すると、次のようなクエリを作成できます。

$users = new User();
$users->where_related('profile', 'name', 'Diego');
$users->get();

プロファイル名が Diego のユーザーが返されます。Eloquent ORMを使用してこれを達成するにはどうすればよいですか? 流暢(純粋なSQL)を使用してこれを行う方法は知っていますが、雄弁を使用してこれを行う方法がわかりません。

編集:このクエリを使用してこの問題を解決しましたが、汚いと感じました。これを行うより良い方法はありますか?

$users = Users::join('profiles', 'profiles.user_id', '=', 'user.id')->where('profiles.name', 'Diego')->get();
4

1 に答える 1

0

テーブルごとにモデルを作成してから、関係を指定する必要があります。

<?php
class User {
    protected $primaryKey = 'id';
    protected $table = 'users';
    public function profile()
    {
        return $this->hasOne('Profile');
    }
}
class Profile {
    protected $primaryKey = 'user_id';
    protected $table = 'profiles';
}
$user = User::where('username', 'Diego')->get();
// Or eager load...
$user = User::with('Profile')->where('username', 'Diego')->get();
?>

Laravel のドキュメントでは、プロセスが非常に明確になっています: http://four.laravel.com/docs/eloquent#relationships

Fluent メソッドは Eloquent で利用可能であり、連鎖できることに注意してください。

于 2013-10-04T16:23:49.820 に答える