【问题标题】:Laravel Eloquent finding models with more than one relation to another model on another table [duplicate]Laravel Eloquent 查找与另一个表上的另一个模型具有多个关系的模型[重复]
【发布时间】:2020-12-29 00:34:47
【问题描述】:

我有两个模型在两个不同的连接上使用不同的表,用户和用户信息。

用户有一个 UserInfo hasMany 关系:

public function userInfo()
{
    return $this->hasMany('path\to\UserInfo','User_ID');
}

和 UserInfo 有一个 User belongsTo 关系:

public function user()
{
    return $this->belongsTo('anotherpath\to\User', 'User_ID', 'User_ID');
}

我想找到具有多个 UserInfo 的第一个用户,但是我相信因为他们位于数据库的不同表上,所以我遇到了问题。

这个电话

$patient = Patient::with('UserInfo')
    ->withCount('UserInfo')
    ->having('UserInfo_count', '>', 1)
    ->first();

对其他关系按预期工作,这是我想要实现的,但不是这个。不同之处在于这两个模型在不同的桌子上。当我在 Tinker 中调用它时,出现错误:

Illuminate/Database/QueryException with message 'SQLSTATE[42S02]:
Base table or view not found: 1146 Table '(TableName).UserInfo'
doesn't exist (SQL: select `User`.*, (select count(*) from `UserInfo`
where `User`.`User_ID` = `eob`.`User_ID`) as `UserInfo_count `User`
having `UserInfo_count` > 1 limit 1)'

有什么想法吗?总的来说,我对 eloquent 和 Laravel 很陌生,如果我有任何术语错误或遗漏了一些简单的东西,我很抱歉。谢谢!

【问题讨论】:

  • 请在您的问题中提及您的表名。
  • 模型总是在不同的桌子上,这就是它的工作原理。我认为您的意思是它们位于不同的数据库中。在您的关系定义中使用setConnection(),就像在副本中一样。另请注意,您的代码最好写成$patient = Patient::whereHas("userInfo")->with("userInfo")->first();

标签: php laravel eloquent


【解决方案1】:

也许您的表名没有正确定义为标准。所以你可以使用表属性来绑定模型中的表名。

定义表名的标准是什么。

Illuminate/Database/Eloquent/Model.php

/**
 * Get the table associated with the model.
 *
 * @return string
 */
public function getTable()
{
    if (isset($this->table)) {
        return $this->table;
    }

    return str_replace('\\', '', Str::snake(Str::plural(class_basename($this))));
}

示例

Table            Model
users            User
user_profiles    UserProfile

另类

在您的 UserInfo 模型中

protected $table = 'your table name';

更多的事情你不需要添加 with() 方法和 withCount() 方法。

$patient = Patient::withCount('UserInfo')->having('UserInfo_count', '>', 1)->first();

【讨论】:

    猜你喜欢
    • 2021-01-07
    • 2013-11-17
    • 2014-04-02
    • 1970-01-01
    • 2023-03-27
    • 2021-09-05
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    相关资源
    最近更新 更多