【问题标题】:Is there any way to reference $this inside an association's conditions?有没有办法在协会的条件下引用 $this ?
【发布时间】:2014-11-15 16:39:43
【问题描述】:

假设我有一个带有 date 列的屏幕截图模型,该列定义了截屏的时间。我还有一个 GameVersion 模型,其中 start_dateend_date 实例方法定义了给定版本的开始和结束。

如果我想要每个 GameVersion 的 screenshots 关联,它返回在其 start_date()end_date() 之间拍摄的所有屏幕截图,我可以这样做吗?

static $has_many = [
    ['screenshots', 'conditions' => ['date >= ? AND date <= ?', $this->start_date(), $this->end_date()]],
];

如果我尝试这样做,我会得到:

Parse error: syntax error, unexpected '$this' (T_VARIABLE), expecting ']'

在 Ruby on Rails 中,这是这样完成的:

has_many :birthday_events, ->(user) { where starts_on: user.birthday }, class_name: 'Event'

【问题讨论】:

    标签: php phpactiverecord


    【解决方案1】:

    您不能将$this 与静态成员一起使用,请改用self::

    【讨论】:

    • 这会导致Parse error: syntax error, unexpected '(', expecting ']'(整行:static $has_many = [['screenshots', 'conditions' =&gt; ['date &gt;= ? AND date &lt;= ?', self::start_date(), self::end_date()]]];)。澄清一下,start_date()end_date() 是实例方法,而不是静态/类方法。
    • @TonyFox 哪个版本的 php?我建议您使用常规语法,以避免出现问题。或者您可能忘记在某处关闭分号
    • 5.4.7,代码的哪一部分不是正则语法?除非你的意思是 array() 而不是 [],我会试试的。
    • 这个版本没问题,检查语法问题是否在这一行之上,比如忘记关闭括号或分号,因为它看起来很好
    • 你能用 [] 创建关联数组吗?尝试用 array() 而不是 [] 替换。看看能不能解决。
    猜你喜欢
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多