尝试排序并获取数据收集

匿名聊天框:

我试图users通过从reports表中传入id 来获取中用户的数据,
我想显示reason的名称reported_userreported_by
运行时的名称,dd($report->all());这表明:

array:2 [▼
  0 => App\Report {#1057 ▼
    #fillable: array:3 [▼
      0 => "reported_by"
      1 => "reported_user"
      2 => "reason"
    ]
    #connection: "sqlite"
    #table: "reports"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: false
    #attributes: array:6 [▶]
    #original: array:6 [▶]
    #changes: []
    #casts: []
    #classCastCache: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #guarded: array:1 [▶]
  }
  1 => App\Report {#1056 ▶}
]

我也面临此错误:-
此集合实例上不存在属性[reported_user]。
同样的道理$reportedBy

这是我的控制器

public function reports()
    {
        $report = Report::all();

        $reportedUser = DB::table('users')
        ->where('id', '=', $report->reported_user)
        ->get();

        $reportedBy = DB::table('users')
        ->where('id', '=', $report->reported_by)
        ->get();



        return view('admin.report', compact('report'));
}

这是我的报告表:

public function up()
    {
        Schema::create('reports', function (Blueprint $table) {
            $table->id();
            $table->integer('reported_by')->unsigned();
            $table->integer('reported_user')->unsigned();
            $table->string('reason');
            $table->timestamps();
        });
    }

谁能告诉我这是否是执行此任务的正确方法,为什么我会收到这样的错误。

水手:

您正在尝试从集合而不是对象的单个实例中绘制属性。

集合$report不是单个对象,而是报告的集合。该集合中的每个报表将具有属性reported_user,但不具有整个集合。

要解决此问题,您可以从数据库中获取单个报告:

 $report = Report::first();

您可以在其中访问reported_user此对象字段,也可以循环查看从原始集合中提取的报告

foreach($report as $r){
  $reportedUser = DB::table('users')
    ->where('id', '=', $r->reported_user)
    ->first();
 }

建议将原始报告集合命名为$reports防止混淆,并表明它是一个集合,而不是单个报告对象。

另请注意,我在循环中做了同样的事情-抓取一个对象,而不是使用first()方法的集合,而不是get()

编辑

上面是一个简单的示例来说明。为了防止许多数据库调用,您还可以执行以下操作:

$reports = Report::pluck('reported_user');

$reportedUsers = DB::table('users')
   ->whereIn('id', $reports)
   ->get();

现在,您已经拥有了所有reported_user细节的集合然后,您可以循环浏览该$reportedUsers集合,并获得每个集合的详细信息。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章