php - Laravel 5 在两列上有很多关系

标签 php laravel eloquent laravel-5

是否可以在两列上建立 hasMany 关系?

我的表有两列,user_idrelated_user_id

我希望我的关系匹配任何一列。

在我的模型中有

public function userRelations()
{
    return $this->hasMany('App\UserRelation');
}

运行查询:select * from user_relations where user_relations.user_id in ('17', '18')

我需要运行的查询是:

select * from user_relations where user_relations.user_id = 17 OR user_relations.related_user_id = 17 

编辑:

我正在使用预先加载,我认为这会影响它的工作方式。

$cause = Cause::with('donations.user.userRelations')->where('active', '=', 1)->first();

最佳答案

我认为完全按照您的要求做是不可能的。

我认为您应该将它们视为单独的关系,然后在模型上创建一个新方法来检索两者的集合。

public function userRelations() {
    return $this->hasMany('App\UserRelation');
}

public function relatedUserRelations() {
    return $this->hasMany('App\UserRelation', 'related_user_id');
}

public function allUserRelations() {
    return $this->userRelations->merge($this->relatedUserRelations);
}

这样您仍然可以在模型上获得预加载和关系缓存的好处。

$cause = Cause::with('donations.user.userRelations', 
        'donations.user.relatedUserRelations')
    ->where('active', 1)->first();

$userRelations = $cause->donations[0]->user->allUserRelations();

关于php - Laravel 5 在两列上有很多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29751859/

相关文章:

database - 为什么我们使用 laravel seed,如果有 migration 和 eloquent 扮演数据库概念的角色?

php - DOMPDF - 背景 url(linux 与 windows)

php - 过期与清除 cookie

php - Mysql 使用 OR 的选择语句

mongodb - Laravel 5.2 + MongoDB + Auth = 用户必须实现 CanResetPassword 接口(interface)

laravel - 为什么软删除实体会出现在查询结果中?

php - 从 ssh2_connect() 断开连接

forms - 使用表单时 `{{ }}` 和 `{!! !!}` 有什么区别?

Laravel 4 处理 404 错误

php - 用 laravel Eloquent 地检索所有记录