Laravel 5.1(雄辩)在使用关系附加或分离不起作用



我在使用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]:找不到基表或视图:1146 表 'sampledb.listuser' 不存在 (SQL: insert 成listuserenteredlistidmodifieduserid) 值 (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('AppModelUser', 'listuser', 'userid', 'listid');
    }
}

即使我在上面设置了连接名称,它仍然在默认数据库中找到该表。很明显,Eloquent 正在处理关系的默认数据库。有人为此解决吗?是我错了还是这真的是拉拉维尔5.1雄辩的错?

终于找到了原因。雄辩很棒。我在 belongsToMany 参数中指定的模型类是错误的。实际上,如下所示。

return $this->belongsToMany('AppModelLUser', 'listuser', 'userid', 'listid');

我推荐Eloquent,因为你可以在Laravel外面使用它。也许,这是 Web 服务开发的好选择。

最新更新