php - laravel 4 中的 3 个模型 - 通过关系 whereHas 查询进行选择

标签 php mysql laravel relationship

我有 3 个模型:

  • 用户
  • 行星
  • 太阳系统

关系:

在用户模型中:

    public function planets() {
        return $this->hasMany('Planet');
    }

在行星模型中:

    public function sunsystem() {
        return $this->belongsTo('Sunsystem');
    }

    public function user() {
        return $this->belongsTo('User');
    }

在sunsystem模型中:

    public function planets() {
        return $this->hasMany('Planet');
    }

现在我想选择所有太阳系以及所有相关行星 但仅限相关行星属于实际用户的太阳系(在本例中 ID 12)。 但我如何得到正确的结果呢? 这是我尝试的,但它只给了我一个太阳系统,但我期望 2 个太阳系统。我认为我的查询是错误的...:

        $s = Sunsystem::whereHas('Planets', function($q) {
            $q->whereHas('User', function ($u) {
                $u->whereUserId(12);
            });
        })->get();

这也不起作用:

     $s = Sunsystem::select('Sunsystems.*')
       ->join('planets','planets.sunsystem_id','=','sunsystems.id')
       ->join('users','users.id','=','planets.user_id')
       ->where('users.id','=',12)
       ->get();

如果有 2 个行星具有不同的 sunsystem_id 但具有相同的 user_id,我只会得到一个 sunsystem,但我希望有两个。

最佳答案

请尝试一下

$s = Sunsystem::select('Sunsystems.*')
     ->join('planets','planets.sunsystem_id','=','Sunsystems.id')
     ->join('users','users.id','=','planets.user_id')
     ->where('users.id','=',12)
     ->get();

关于php - laravel 4 中的 3 个模型 - 通过关系 whereHas 查询进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29298666/

相关文章:

mysql - 如何设置在线网络服务跟踪(Grafana?)

mysql - 通过交叉引用和自引用从多个表中进行选择[脑力破解者]

php - 在 Laravel 项目中使用 Drupal API 时函数重新声明错误

php - 在 PHP 中匹配关键字

mysql - Laravel 查询生成器 - 日期查询不起作用

php - 在 Laravel Eloquent 中扩展模型

php - Ubuntu Lamp - 代理 - 防火墙 - Joomla curl 和 fsockopen 无法工作

php - fatal error : Using $this when not in object context in

php - 错误 : Duplicate entry '1' for key 'r_id'

php - 你能在 SQL 案例中使用 php 吗?