Summary
尝试调用关系时收到以下错误:
类Illuminate对象\ Database \ Eloquent \ Relations \ BelongsToMany无法转换为字符串
我的设置非常基本,包含两个模型, User
和 Role
.
User Model [User.php]
<?php
use Illuminate\Auth\UserInterface;
class User extends Eloquent implements UserInterface {
protected $table = 'users';
protected $hidden = array('password');
protected $fillable = array('id', 'username', 'password');
public function getAuthIdentifier() {
return $this->getKey();
}
public function getAuthPassword() {
return $this->password;
}
}
Role Model [Role.php]
<?php
class Role extends Eloquent {
protected $table = "roles";
protected $fillable = array(
'id',
'code',
'name'
);
public function foo() {
return $this->belongsToMany('User', 'map_role_user', 'role_id', 'user_id');
}
}
最后我在routes文件中调用方法 foo
,例如:
Route::get('role', function() {
return Role::find(1)->foo();
});
2 回答
从
https://laravel.com/docs/5.3/eloquent-relationships或https://laravel.com/docs/4.2/eloquent#relationships
如果将集合强制转换为字符串,则它将作为JSON返回:
如果您不想为查询添加更多约束,则必须使用
dynamic properties
概念 . 所以,如果要添加更多约束,请执行此操作