【问题标题】:Property does not exist in collection while using belongsToMany in laravel eloquent在laravel eloquent中使用belongsToMany时,集合中不存在属性
【发布时间】:2021-02-24 19:02:39
【问题描述】:

我正在使用 Laravel 8.X 和 eloquent 开发一个网络应用程序。

我有一个数据透视表“portal_event_users”

我正在尝试向portal_event_users 表模型中的portal_users 添加belongsToMany 关系。

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class EventUser extends Model
{
    use HasFactory;
    protected $table = 'portal_event_users';
    
      public function users()
    {
        return $this->belongsToMany(User::class);
    }
    
    public function events()
    {
        return $this->belongsToMany(Event::class);
    }
}

我在控制器中有以下语句

$eventusersobj = \App\Models\EventUser::select('*')
                                    ->where('event_id', '=', $event_id)
                                    ->get();
                    
                    $response =  $eventusersobj->users->keyBy('id');

返回以下错误

此集合实例上不存在属性 [用户]。

有人可以建议我如何更改此错误吗?

提前致谢

【问题讨论】:

  • 您的语句将一个集合返回给 $eventusersobj,因此您需要将其用作集合,例如使用 for 循环进行迭代或使用 $eventusersobj->first() 获取第一项。

标签: laravel eloquent


【解决方案1】:

作为返回集合,你可以使用pluck()

$eventusersobj->pluck('users')->each(function($user){
    $user->keyBy('id');
})

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 2018-02-25
    • 2021-09-23
    • 2018-08-10
    相关资源
    最近更新 更多