首页 文章

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

提问于
浏览
1

Summary

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

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

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

User Model [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 Model [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');
    }
}

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

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

2 回答

  • 1

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

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

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

    如果您不想为查询添加更多约束,则必须使用 dynamic properties 概念 . 所以,

    $user = App\User::find(1);
    
    foreach ($user->posts as $post) {
        //
    }
    

    如果要添加更多约束,请执行此操作

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

相关问题