【问题标题】:Laravel 4.2 HasMany Relationship using LikeLaravel 4.2 HasMany 使用 Like 的关系
【发布时间】:2015-04-23 19:47:44
【问题描述】:

我想知道在 Laravel 4.2 中使用 HasMany 关系时是否可以设置运算符。

我正在使用用户表和电子邮件日志表。日志表有一个以序列化格式存储的用户 ID(因为日志中可能存储多个用户 ID)。

用户表

+---------+
| user_ID |
+---------+
|       1 |
|       2 |
+---------+

邮件日志表

+----+--------------------+
| ID |       user_ID      |
+----+--------------------+
|  1 | a:1:{i:0;s:1:"2";} |
|  2 | a:1:{i:0;s:1:"1";} |
+----+--------------------+

我是否能够将 hasMany 关系与“Like”运算符而不是等于运算符一起使用来返回正确的电子邮件日志 ID?语句会写成下面这样吗?

return $this->hasMany('emailLog', 'user_ID', '%user_ID%', 'LIKE');

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    使用 where 子句返回连接表的正确方法是:

    return $this->hasMany('emailLog','user_id')->where('user_id', 'LIKE', '%user_id%');

    【讨论】:

    • 这不起作用,因为生成的 SQL 是 select * from [emailLog] where [user_ID] LIKE '%userID%' and [emailLog].[user_ID] in ('1')。 SQL 需要像 select * from [emailLog] where [user_ID] LIKE '%userID%'
    • 在这种情况下,hasMany 不适合查询,方法 EmailLog::where('user_id', 'LIKE', '%'.$this->user_id.'%' );应该这样做。
    【解决方案2】:

    我找到了一种方法来做类似的事情

    class User extends Model
    {
        public function emailLogs()
        {
            // old code
            // return $this->hasMany(EmailLogs::class, 'user_ID');
    
            // Replace HasMany by like query
            return EmailLogs::where('user_ID', 'LIKE', "%{$this->user_ID}%");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 1970-01-01
      • 2014-10-29
      • 2013-11-14
      • 1970-01-01
      • 2021-12-14
      • 2020-03-25
      • 2021-03-22
      • 2021-09-24
      相关资源
      最近更新 更多