2013-12-24 48 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()