繁体   English   中英

laravel中的一对多关系

[英]one to many relationships in laravel

每个行业有许多项目每个项目仅属于一个行业

行业表的列如下:

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显示项目名称和行业名称(查看)

我已经创建了项目和行业模型。 如何在我的视图中显示结果?

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');
    }
}

像这样 ...

$Industry = App\Industry ::find(1);

echo $Industry ->Project ->project_name;

https://laravel.com/docs/5.5/eloquent-relationships#one-to-many

请尝试在Industry.php中将方法“项目”重命名为“项目”,因为它是“ 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

如果特别是您只想要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();

希望这会帮助你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM