Laravel ORM关系方法'BelongsToMany'抛出错误

Chr*_*ris 1 php orm laravel laravel-4

摘要

尝试调用关系时收到以下错误:

类Illuminate\Database\Eloquent\Relations\BelongsToMany的对象无法转换为字符串

我的设置非常基础,包含两个模型,UserRole.

用户模型[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;
    }
}
Run Code Online (Sandbox Code Playgroud)

角色模型[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');
    }
}
Run Code Online (Sandbox Code Playgroud)

最后我foo在routes文件中调用方法,例如:

Route::get('role', function() {
        return Role::find(1)->foo();  
    });
Run Code Online (Sandbox Code Playgroud)

小智 6

https://laravel.com/docs/5.3/eloquent-relationshipshttps://laravel.com/docs/4.2/eloquent#relationships

如果将集合强制转换为字符串,则它将作为JSON返回:

<?php
$roles = (string) User::find(1)->roles;
Run Code Online (Sandbox Code Playgroud)