簡體   English   中英

Laravel ORM關系方法'BelongsToMany'拋出錯誤

[英]Laravel ORM relationship method 'BelongsToMany' throwing error

摘要

嘗試調用關系時收到以下錯誤:

無法將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;
    }
}

榜樣[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-relationshipshttps://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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM