【问题标题】:How can I get the parent model data inside of a local scope?如何在本地范围内获取父模型数据?
【发布时间】:2019-05-29 12:20:32
【问题描述】:

$users$students 之间存在多对多关系。如果$student 处于活动状态且$user 处于活动状态,则认为学生处于活动状态。

当我调用$user->students()->active 时,我可以在不传递参数的情况下在作用域内获取$user 模型吗?示例如下:

class User extends Model {
    // Normal model stuff

    function students() {
        return $this->belongsToMany('students', 'user_students');
    }
}

class Student extends Model {
    // Normal model stuff

    function scopeActive($query) {
        // Can I get the $user model here without a parameter?
    }
}

所以我想检查 scopeActive 函数中的用户状态,这将改变查询。

【问题讨论】:

  • 您可以在模型中存储对 User 的引用吗?
  • @atoms 那会是什么样子?

标签: php laravel eloquent


【解决方案1】:

首先,当您尝试阅读时,这种关系听起来很奇怪:一个用户有很多学生,一个学生有很多用户,但无论如何。

我不认为您可以获得对调用者的引用,但您可以将参数传递给自定义范围,即 dynamic scopes

所以你的范围可以是:

public function scopeActive($query, $user)
{
   // here you have reference to the $user
}

你可以这样称呼它:

Student::active($user);

【讨论】:

  • 是的,我同意这很奇怪,但出于商业原因,它是这样的。我上面说过我是在不传递参数的情况下寻求一种方式。我想知道是否有办法获取 eloquent 使用的对父级的引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
  • 2021-06-09
  • 1970-01-01
  • 2020-11-20
  • 2013-10-03
相关资源
最近更新 更多