简体   繁体   中英

Eloquent's Many-to-Many inverse is not fetched

I have 2 models namely Role and User models. With the following code respectively on each models:

Role.php:

public function users(){
    return $this->belongsToMany('\Models\User', 'rbac_user_roles','role_id','username');
}

..

User.php:

public function roles(){
    return $this->belongsToMany('\Models\RBAC\Role', 'rbac_user_roles','username','role_id');
}

but when I try to dump the data like so:

$model = Role::find( 1);
$model2 = User::find( 'test_user');

var_dump( $model->users->toArray() );
var_dump( $model2->roles->toArray() );

The $model->users->toArray() finds actual data while $model2->roles->toArray() returns nothing. Which is odd because I am pretty sure that the code works correctly. With this, I would like to ask, is there an effect if the primary key for the database is a string for eloquent? because I believe this is the culprit here. If so, what can i do to remedy the situation?

The situation needs/has the following conditions -> Can't add a new column for index enabled auto-increment key for users table -> All table and data is correctly setup, as the first var_dump() actually dumps the correct data.

Thanks,

Jan

EDIT:

I also tried the following in getting the User:

$model2 = User::where( 'username', 'test_user')->get()->first();

Note: The primary key for the table Users is a string

Apparently, Eloquent is quite strict with non-increment primary keys. You should set the attribute for increments to false in the Eloquent Model like:

public $incrementing = false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM