[英]BelongsTo relationship in laravel
我正在尝试建立一对多关系,每个客户可以分配给多个条目,这是我的迁移表
客户表:
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('idtype');
$table->string('idnumber');
$table->string('company');
$table->timestamps();
这是我的受让人表:
Schema::create('assignees', function (Blueprint $table) {
$table->increments('id');
$table->string('cabinet');
$table->time('timein');
$table->time('timeout');
$table->string('refnumber');
$table->timestamps();
$table->integer('customer_id')->unsigned()->index()->nullable();
这是我的受让人控制器所属的函数:
class Assignee extends Model
{
//
protected $fillable = [
'cabinet', 'customer_id','timein','timeout','refnumber',
];
public function cust()
{
return $this->belongsTo('App\Customer');
}
}
这是我的index.blade.php
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Entry id:</th>
<th>Person Name</th>
<th>Referance No:</th>
<th>timein</th>
<th>timeout</th>
<th width="280px">Action</th>
</tr>
@foreach ($assignees as $assignee)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $assignee->id }}</td>
<td>{{$assignee->customer-name}}</td>
<td>{{ $assignee->refnumber }}</td>
<td>{{ $assignee->timein }}</td>
<td>{{ $assignee->timeout }}</td>
运行页面时出现以下错误:
Use of undefined constant name - assumed 'name' (View: /Users/user/Documents/Laravel/blog/resources/views/assignees/index.blade.php)
创建“受让人时,laravel不会强制执行关系检查,
我究竟做错了什么? 我应该在迁移文件夹中声明该关系还是在模型中具有足够的关系?
您的问题在这里<td>{{$assignee->customer-name}}</td>
它应该是<td>{{$assignee->cust->name}}</td>
而您错过了此->
因此它假定该名称是连续的。
您的代码中有两个问题。
此行中有语法错误。 这引发了上述问题。
<td>{{$assignee->customer-name}}</td>
它应该是
<td>{{$assignee->customer->name}}</td>
但是,你作为命名的关系cust
不是customer
。 因此,您也需要修复该问题。
<td>{{$assignee->cust->name}}</td>
这应该修复您的代码。
您应该尝试一下;
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Entry id:</th>
<th>Person Name</th>
<th>Referance No:</th>
<th>timein</th>
<th>timeout</th>
<th width="280px">Action</th>
</tr>
@foreach ($assignees as $assignee)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $assignee->id }}</td>
<td>{{$assignee->customer->name}}</td>
<td>{{ $assignee->refnumber }}</td>
<td>{{ $assignee->timein }}</td>
<td>{{ $assignee->timeout }}</td>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.