我有 2 张桌子:公告和公司。company_id 是公告表上的外键。
我有这样的控制器设置:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Announcement;
use App\Models\Company;
class AnnouncementController extends Controller
{
public function upcomingIssues()
{
$announcement = Announcement::orderBy('id','desc')->with('companies')->get();
return view('pages.upcoming-issues',compact('announcement'));
}
}
公告模型如下:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Announcement extends Model
{
protected $table = 'announcements';
public function company()
{
return $this->belongsTo(Company::class, 'company_id');
}
// Usage: $announcement->company
public function getCompanyAttribute()
{
return $this->companies->where('id','company_id')->get();
}
}
公司模式如下
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $table = 'companies';
public function announcement()
{
return $this->hasMany(Announcement::class, 'company_id');
}
}
最后查看表格如下:
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Company</th>
</tr>
</thead>
<tbody>
@foreach($announcement as $announce)
<tr>
<th>{{ $loop->iteration }}</th>
<td>{{ $announce->company }}</td>
</tr>
@endforeach
</tr>
</tbody>
</table>
当我尝试访问此页面时,我收到以下消息“
调用模型 [App\Models\Announcement] 上的未定义关系 [公司]。
"