【问题标题】:Eloquent ORM querying relationshipEloquent ORM 查询关系
【发布时间】:2013-10-04 15:49:12
【问题描述】:

假设我有两个这样的表:

users:
    - id
    - username

profiles:
    - user_id
    - name

使用 datamapper ORM codeigniter 我可以编写如下查询:

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

它会返回配置文件名称为 Diego 的用户。如何使用 Eloquent ORM 实现这一目标?我知道如何使用 fluent(pure sql) 做到这一点,但不知道如何使用 eloquent 做到这一点。

编辑:我使用这个查询解决了这个问题,但感觉很脏,有没有更好的方法来做到这一点?

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

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您必须为每个表创建模型,然后指定关系。

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

    请注意,Eloquent 可以使用 Fluent 方法并且可以链接,例如where()->where()->orderBy()->etc....

    【讨论】:

    • 用你的回答我写了这个查询: User::with('profile')->where('name', 'Diego")->get(); 但它返回了这个错误: SQLSTATE [42S22]:未找到列:1054 'where 子句'中的未知列 'name'(SQL:select * from users where name = ?)(绑定:数组(0 => 'Diego',))
    • 这里的所有查询都将在用户表上运行,而不是在配置文件关系上运行。这不是 OP 想要的。
    猜你喜欢
    • 2015-01-21
    • 1970-01-01
    • 2017-03-16
    • 2015-04-09
    • 2023-04-01
    • 2013-11-30
    • 1970-01-01
    • 2015-10-29
    • 2021-06-10
    相关资源
    最近更新 更多