2013-12-24 45 views
1

摘要Laravel ORM关系法“BelongsToMany”抛出错误

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

类照亮\数据库对象\雄辩\关系\ BelongsToMany 不能转换成字符串

我的设置是非常基本的,包括两个型号,User和的。

用户模型[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'); 
    } 
} 

最后我打电话路由文件的方法foo,例如:

Route::get('role', function() { 
     return Role::find(1)->foo(); 
    }); 
+6

试试这个角色'::发现(1) - > foo' – Anam

+0

这正是它。干杯! – Chris

回答

5

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

如果集合被转换为字符串,将返回JSON:

<?php 
$roles = (string) User::find(1)->roles; 
+0

我是涂料!谢谢!我花了一个小时盯着那个。谢谢 – Chris

+0

出于兴趣,角色返回'user'加上数据透视表'map_role_user'中的数据,而不是'role'。我需要手动迭代,是否正确? – Chris

+1

User :: find(1) - >角色将返回有关角色的所有数据,但不包括用户。如果您需要用户和角色的信息,您可以执行$ user = User :: find(1),然后您可以使用$ users作为Collection并调用$ users-> roles来显示有关角色的数据该用户。 –

1

如果你不想要进一步限制添加到查询,那么你必须使用dynamic properties的概念。所以,

$user = App\User::find(1); 

foreach ($user->posts as $post) { 
    // 
} 

如果你想添加更多的约束条件,然后做这个

App\User::find(1)->posts()->where('title', 'LIKE', '%Best%')->get()