摘要
尝试调用关系时收到以下错误:
类Illuminate \ Database \ Eloquent \ Relations \ BelongsToMany的对象 无法转换为字符串
我的设置非常基础,由两个模型User
和Role
组成。
用户模型[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.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();
});
答案 0 :(得分:6)
来自
https://laravel.com/docs/5.3/eloquent-relationships或https://laravel.com/docs/4.2/eloquent#relationships
如果将集合强制转换为字符串,它将以JSON:
的形式返回<?php
$roles = (string) User::find(1)->roles;
答案 1 :(得分:1)
如果您不想为查询添加更多约束,则必须使用dynamic properties
概念。所以,
$user = App\User::find(1);
foreach ($user->posts as $post) {
//
}
如果您想添加更多约束,请执行此操作
App\User::find(1)->posts()->where('title', 'LIKE', '%Best%')->get()