Ad

Laravel 5.1 (Eloquent) In Using Relationship Attaching Or Detaching Not Working

- 1 answer

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.

$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))

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?

Ad

Answer

Finally found the reason. Eloquent was wonderful. The model class I specified in the belongsToMany parameter was wrong. It was actually, as belows.

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.

Ad
source: stackoverflow.com
Ad