这可能是路由代码
Route::get('/dashboard',['middleware' => 'auth', function () {
$links = App\Website_links::where('website_id',1)->get();
return view('user.dashboard',['links_data'=>$links]);
}]);
和website_link模型代码是
class Website_links extends Model
{
public $timestamps = false;
protected $table = 'website_links';
public function project()
{
return $this->belongsTo('App\Website','website_id')
->select('project_name','project_status');
}
}
并查看代码
@foreach($links_data as $links)
<tr>
<td><a href="">{{$links['page_url']}}</a></td>
<td>{{$links['project']}}</td>// here i want to display project_name from website table
</tr>
@endforeach
数据库架构:
website : id,project_name,project_status
website_links: id, page_url, website_id //here website_id is forign key.
现在它正确显示page_url但是
{{$links['project']}} display {"project_name":"Project1","id":45}
我想显示project_name值,如project1而不是整个数组
{"project_name":"Project1","id":45}
更改
$links['project'] to $link->project->project_name
@foreach($links_data as $links)
<tr>
<td>
<a href="">{{$links['page_url']}}</a>
</td>
<td>
{{$links->project->project_name}}
</td>// here i want to display project_name from website table
</tr>
@endforeach
并将您的查询更改为以下以防止N + 1查询问题
$links = App\Website_links::with('project')->where('website_id',1)->get();