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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20753192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:48:02  来源:igfitidea点击:

Laravel ORM relationship method 'BelongsToMany' throwing error

phpormlaravellaravel-4

提问by Chris

Summary

概括

I am receiving the following error when trying to call the relationship:

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

Object of class Illuminate\Database\Eloquent\Relations\BelongsToMany could not be converted to string

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

My setup is very basic, and consists of two models, Userand Role.

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

User Model [User.php]

用户模型 [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]

角色模型 [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');
    }
}

And finally I'm calling the method fooin the routes file, example:

最后我调用foo路由文件中的方法,例如:

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

回答by Daniel Albornoz

From

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

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

If a collection is cast to a string, it will be returned as JSON:

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

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

回答by Chaudhry Waqas

If you dont want to add further constraints to the query then you have to use dynamic propertiesconcept. So,

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

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

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

If you want to add more constraints then do this

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

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