Laravel 5.4:无法从关系中检索数据
Posted
技术标签:
【中文标题】Laravel 5.4:无法从关系中检索数据【英文标题】:Laravel 5.4: Cannot retrieve data from a relationship 【发布时间】:2018-01-06 10:52:01 【问题描述】:我试图通过将每个名称存储在两个 UNION 表(访问和报告)的数组中来显示每个工单的受让人的名称(用户表中的外键),但它给了我这个错误。错误异常 未定义的属性:stdClass::$assignee。
//HomeController
$accesses = DB::table('accesses')
->select(array('id', 'fullname','emp_id','shift','state','resolved_at', 'closed_at','assigned_to'))
->where('state','=','Assigned');
$all = DB::table('reports')
->select(array('id', 'fullname','emp_id','shift','state','resolved_at', 'closed_at','assigned_to'))
->union($accesses)
->where('state', '=', 'Assigned')
->get();
$names[] = array();
foreach ($all as $one)//store in array to display in a chart
$names[] = $one->assignee->name; //error here
//Report Model
public function assignee()
return $this->belongsTo(User::class, 'assigned_to');
//Access Model
public function assignee()
return $this->belongsTo(User::class, 'assigned_to');
//Report Migration
public function up()
Schema::create('reports', function (Blueprint $table)
$table->increments('id');
$table->integer('user_id')->nullable();
$table->string('fullname');
$table->string('emp_id');
$table->string('shift');
$table->longText('report');
$table->string('status')->default('Pending'); //Pending, Approved
$table->string('state')->default('Open'); //Open, Assigned, Resolved, Closed
$table->date('resolved_at')->nullable();
$table->date('closed_at')->nullable();
$table->integer('assigned_to')->nullable();
$table->longText('action')->nullable();
$table->timestamps();
);
//Access Migration
public function up()
Schema::create('accesses', function (Blueprint $table)
$table->increments('id');
$table->integer('user_id')->nullable();
$table->string('fullname');
$table->string('emp_id');
$table->string('shift');
$table->string('request');
$table->longText('note')->nullable();
$table->string('status')->default('Pending'); //Pending, Approved
$table->string('state')->default('Open'); //Open, Assigned, Resolved, Closed
$table->date('resolved_at')->nullable();
$table->date('closed_at')->nullable();
$table->integer('assigned_to')->nullable();
$table->longText('action')->nullable();
$table->timestamps();
);
It gives me this error
The results should be like this
【问题讨论】:
您正在使用DB
外观,而不是在模型上进行查询。因此,您将无法访问任何关系。
您只需要受让人的姓名吗?如果是这样,为什么要查询所有字段?如果没有,请在您的问题中添加更多信息。
【参考方案1】:
你应该使用merge
的收集方法:
$accesses = Access::select(array('id', 'fullname','emp_id','shift','state','resolved_at', 'closed_at','assigned_to'))
->where('state','=','Assigned')
->get();
$reports = Report::select(array('id', 'fullname','emp_id','shift','state','resolved_at', 'closed_at','assigned_to'))
->where('state', '=', 'Assigned')
->get();
$all = $accesses->merge($reports);
【讨论】:
但如果我使用 eloquent,则联合将不起作用,因为表的列数不同。 更新了我的答案,可能会对你有所帮助。 @GrantGubatan @GrantGubatan 这行不通。 Eloquent 集合基于模型主键合并结果。如果两个结果集中存在相同的主键,则会被覆盖。以上是关于Laravel 5.4:无法从关系中检索数据的主要内容,如果未能解决你的问题,请参考以下文章