[英]Laravel attach returns undefined method for belongsToMany relationship
[英]Laravel ORM relationship method 'BelongsToMany' throwing error
摘要
嘗試調用關系時收到以下錯誤:
無法將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');
}
}
最后,我在路由文件中調用方法foo
,例如:
Route::get('role', function() {
return Role::find(1)->foo();
});
從
https://laravel.com/docs/5.3/eloquent-relationships或https://laravel.com/docs/4.2/eloquent#relationships
如果將集合強制轉換為字符串,則將其作為JSON返回:
<?php
$roles = (string) User::find(1)->roles;
如果您不想向查詢添加更多約束,則必須使用dynamic properties
概念。 所以,
$user = App\User::find(1);
foreach ($user->posts as $post) {
//
}
如果要添加更多約束,請執行此操作
App\User::find(1)->posts()->where('title', 'LIKE', '%Best%')->get()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.