每个行业都有很多项目 每个项目只属于一个行业
industries表包含以下列:
id, industry_name, industry_code, created_at, updated_at
项目表包含如下列:
id, industry_id (foreign key), user_id, project_name, project_start_date, project_end_date, created_at, updated_at
我想在index.blade.php
(查看)
我创建了Project&行业模式。如何在我的视图中显示结果?
Industry.php model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Industry extends Model
{
public function project()
{
return $this->hasMany('App\Models\Project');
}
}
Project.php model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
public function industry()
{
return $this->belongsTo('App\Models\Industry');
}
}
答案 0 :(得分:0)
$Industry = App\Industry ::find(1);
echo $Industry ->Project ->project_name;
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many
答案 1 :(得分:0)
尝试将您的方法“project”重命名为Industry.php中的“projects”,因为它是“hasMany”关系。这可以防止你犯错误。
在你的控制器中,比如PagesController.php
public function index() {
// find an industry with id of 1
$Industry = App\Industry ::find(1);
return view('some_view',compact('industry'));
}
因此,在您看来,由于某个行业有许多项目,您可以访问它们并通过$Industry->projects
进行循环。但是,您应该考虑急切加载它们以防止n + 1问题。将您的查询编辑为$Industry = App\Industry ::with('projects')->find(1);
详细了解加载https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many
答案 2 :(得分:0)
如果具体您只想要project_name和industry_name 试试这个 -
$result = App\Industry::with(array('projects'=> function($query){
$query->addSelect(['project_name']);
}))
->where('industry.id',$id)
->get([industry_name]);
其他所有记录都试试这个 -
$result = App\Industry::with('projects')
->where('industry.id',$id)
->get();
希望这会对你有所帮助。