I'm having problems in using Laravel 5.1's Eloquent. I have 2 databases, and 2 model classes are using a different database (that is not default database). It is working well for simple CRUD, but when I use relationship, it causes an error.
我在使用Laravel 5.1的Eloquent时遇到了问题。我有2个数据库,2个模型类使用不同的数据库(不是默认数据库)。它适用于简单的CRUD,但是当我使用关系时,它会导致错误。
$list->users()->attach($nListUser->id, [
'entered' => $user->createdDate,
'modified' => date('Y-m-d H:m:s'),
]);
Or
要么
$list->users()->detach($nListUser->id);
Error code is
错误代码是
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))SQLSTATE [42S02]:找不到基表或视图:1146表'sampledb.listuser'不存在(SQL:insert into listuser(输入,listid,modified,userid)值(2012-06-17 18:34:58 ,52275,2016-01-18 02:01:46,6))
This is my model class file.
这是我的模型类文件。
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');
}
}
Eventhough I set connection name above, it is still finding the table in default database. It is clear that the Eloquent is working on default database for relationship. Has anyone solution for this? Am I wrong or Is this really Laravel 5.1 Eloquent's fault?
虽然我在上面设置了连接名称,但它仍然在默认数据库中找到该表。很明显,Eloquent正在研究默认的关系数据库。有没有人解决这个问题?我错了还是这真的是Laravel 5.1 Eloquent的错?
1 个解决方案
#1
0
Finally found the reason. Eloquent was wonderful. The model class I specified in the belongsToMany parameter was wrong. It was actually, as belows.
终于找到了原因。雄辩很精彩。我在belongsToMany参数中指定的模型类是错误的。实际上,如下所示。
return $this->belongsToMany('App\Model\LUser', 'listuser', 'userid', 'listid');
I recommend Eloquent because you can use it outside Laravel. Maybe, good choice for web service development.
我推荐Eloquent,因为你可以在Laravel之外使用它。也许,Web服务开发的不错选择。
#1
0
Finally found the reason. Eloquent was wonderful. The model class I specified in the belongsToMany parameter was wrong. It was actually, as belows.
终于找到了原因。雄辩很精彩。我在belongsToMany参数中指定的模型类是错误的。实际上,如下所示。
return $this->belongsToMany('App\Model\LUser', 'listuser', 'userid', 'listid');
I recommend Eloquent because you can use it outside Laravel. Maybe, good choice for web service development.
我推荐Eloquent,因为你可以在Laravel之外使用它。也许,Web服务开发的不错选择。