php - Laravel 5.1( Eloquent )在使用关系附加或分离时不起作用

标签 php mysql database laravel

我在使用 Laravel 5.1 的 Eloquent 时遇到问题。我有 2 个数据库,2 个模型类使用不同的数据库(不是默认数据库)。 它对于简单的 CRUD 运行良好,但是当我使用关系时,它会导致错误。

$list->users()->attach($nListUser->id, [
                            'entered' => $user->createdDate,
                            'modified' => date('Y-m-d H:m:s'),
                            ]);

或者

$list->users()->detach($nListUser->id);

错误代码为

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sampledb.listuser' doesn't exist (SQL: insert into listuser (entered, listid, modified, userid) values (2012-06-17 18:34:58, 52275, 2016-01-18 02:01:46, 6))

这是我的模型类文件。

class ListUser extends Model
{

    protected $connection = 'listdbconnection';
    protected $table = 'listuser';

    public $timestamps = false;

}
class PList extends Model
{
    protected $connection = 'listdbconnection';
    protected $table = 'list';

    public $timestamps = false;

    public function users(){
        return $this->belongsToMany('App\Model\User', 'listuser', 'userid', 'listid');
    }
}

尽管我在上面设置了连接名称,但它仍然在默认数据库中查找该表。很明显,Eloquent 正在研究关系的默认数据库。 有没有人解决这个问题?是我错了还是这真的是 Laravel 5.1 Eloquent 的错?

最佳答案

终于找到原因了。 Eloquent 太好了。我在belongsToMany参数中指定的模型类是错误的。 事实上,如下所示。

return $this->belongsToMany('App\Model\LUser', 'listuser', 'userid', 'listid');

我推荐 Eloquent,因为你可以在 Laravel 之外使用它。也许,Web 服务开发的不错选择。

关于php - Laravel 5.1( Eloquent )在使用关系附加或分离时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34846652/

相关文章:

mysql - 在 WHERE 子句中使用列别名

java - c3p0 连接池,无需在 checkin 或 checkout 时进行测试

php - 获取时 PDO 自动别名?

php - 为数据库条目生成计数器代码

c# - 我如何从 mysql 数据库获取和插入格式化文本并使用它

mysql - SQL插入语句给出未知列错误

mysql - 提高 pentaho 表输入步骤性能

database - Kubernetes 和云数据库

PHP:从base64字符串中获取图像并将其存储在路径中

javascript - 刷新歌曲标题而不重新加载整个页面