【问题标题】:Laravel ORM relationship method 'BelongsToMany' throwing errorLaravel ORM关系方法'BelongsToMany'抛出错误
【发布时间】:2014-01-12 05:48:07
【问题描述】:

总结

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

类 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();  
    });

【问题讨论】:

  • 试试这个Role::find(1)-&gt;foo
  • 就是这样。干杯!

标签: php orm laravel laravel-4


【解决方案1】:

来自

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

如果一个集合被转换成一个字符串,它将以 JSON 形式返回:

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

【讨论】:

  • 我是个笨蛋!谢谢!我已经花了一个小时盯着它。谢谢
  • 出于兴趣,角色返回 user 加上数据透视表中的数据 map_role_user,但不返回 role。我需要手动迭代,对吗?
  • User::find(1)->roles 将返回有关角色的所有数据,但不返回有关用户的任何数据。如果您需要用户和角色的信息,您可以执行 $user = User::find(1) 然后您可以使用 $users 作为集合并调用 $users->roles 来显示有关角色的数据那个用户。
【解决方案2】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-22
    • 2018-05-19
    • 2018-03-08
    • 2021-03-22
    • 2021-10-17
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多