我在使用 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/