我试图通过从reports
表传入ID从users
表中获取用户数据。
我希望在运行dd($report->all())时显示
,reported_user
原因reported_by
和reported_by
的名称;它显示如下内容:-
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 ▶}
]
我还面临此错误:-
此集合实例上不存在Property[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
,但不具有整个集合。
要进行修复,您可以从DB获取单个报告:
$report = Report::first();
其中您将有权访问此对象的reported_user
字段,或者可以对从原始集合中绘制的报表进行循环:
foreach($report as $r){
$reportedUser = DB::table('users')
->where('id', '=', $r->reported_user)
->first();
}
建议将原始报表集合命名为$reports
,以防止混淆,并显示它是一个集合,而不是单个报表对象。
另外--注意,我在循环中做了同样的事情--使用first()
方法而不是get()
获取对象,而不是集合。
编辑:
上面是一个简单的例子来解释。 要防止多次DB调用,还可以这样做:
$reports = Report::pluck('reported_user');
$reportedUsers = DB::table('users')
->whereIn('id', $reports)
->get();
您现在有了一个包含所有reported_user
的完整详细信息的集合。 然后,可以对$ReportedUsers
集合进行循环,并获取每个集合后面的详细信息。