Mysql 正在尝试对数据进行排序并获取数据集合
我试图通过从Mysql 正在尝试对数据进行排序并获取数据集合,mysql,database,laravel,eloquent,Mysql,Database,Laravel,Eloquent,我试图通过从reportstable中传入id,从users表中获取用户的数据 我想显示原因报告用户的姓名和报告用户的姓名 当我运行dd($report->all())时它显示以下内容:- array:2 [▼ 0 => App\Report {#1057 ▼ #fillable: array:3 [▼ 0 => "reported_by" 1 => "reported_user" 2 => "reason" ]
reports
table中传入id,从users
表中获取用户的数据我想显示
原因
报告用户的姓名和报告用户的姓名当我运行
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 ▶}
]
我也面临此错误:-
此集合实例上不存在属性[报告的用户]。
$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\u user
,但不包括整个集合
要修复此问题,您可以从数据库中获取单个报告:
$report = Report::first();
您可以在其中访问此对象的reported\u user
字段,也可以循环使用从原始集合中绘制的报告:
建议将原始报表集合命名为$reports
,以避免混淆,并表明它是一个集合,而不是单个报表对象
另外-注意,我在循环中也做了同样的事情-使用first()
方法而不是get()
抓取一个对象,而不是一个集合
编辑:
以上是一个简单的例子来解释。要防止许多DB调用,还可以执行以下操作:
$reports = Report::pluck('reported_user');
$reportedUsers = DB::table('users')
->whereIn('id', $reports)
->get();
现在,您拥有了所有报告的\u用户
的完整详细信息集合。然后,您可以循环使用该$reportedUsers
集合,并获取每个集合背后的详细信息。这不就是给我一个用户吗?因为我想显示所有报告的_用户和报告的_byYes的详细列表,每个循环一个用户。问题是您最初使用$report=report::all()绘制集合
和正在尝试从整个集合中获取报告的用户。如果您对该集合使用上面的循环,并将每个$reportedUser
添加到一个数组或用户集合中,您将拥有所有报告用户的列表。您很接近-它会工作-您只需要通过循环工作,而不是$reportedUser
grab中的单个对象。当然,您可以收紧此代码以获取所有ID-让我编辑答案并向您展示。是的,这一切都是有道理的。但通常当我在集合中运行dd时,我得到的是值,但在这种情况下,dd($report->all())代码>我看不到任何值为什么?你介意帮我回答另一个问题吗?如果是,那么这里的链接:-很乐意帮助。我还要看另一个问题。。。不知道我是否知道这件事,但我会看一看的!
$reports = Report::pluck('reported_user');
$reportedUsers = DB::table('users')
->whereIn('id', $reports)
->get();