【问题标题】:How to use laravel relations to get data from database如何使用 laravel 关系从数据库中获取数据
【发布时间】:2018-10-24 10:23:41
【问题描述】:

我正在一个主页上工作,我必须在其中显示功能类别供应商滑块。 听到就是我想要的:

我想从类别表中获取随机的 3 个特色类别,其中每个类别有 6 个供应商,我也想显示这些供应商。

数据库结构:

类别表包含is_featured 标志。

id  | is_featured

1   |   1
2   |   1
3   |   1
4   |   1
... so on

我有供应商类别表,我在其中映射了供应商和那里的类别。

SupplierCategoryMappingTable

id  | sup_id | cat_id
1   |   1    |  1
2   |   2    |  2
3   |   3    |  3
4   |   4    |  4
5   |   5    |  5
...so on

还有供应商表,其中我有供应商的详细信息。

供应商表

id  | sup_name ....Other details
1   | ABC
2   | DEF
3   | HIJ
4   | LLK
5   | OPQ
6   | SDE
...so on 

到目前为止我已经尝试过。

我想给hasMany Relation 但得到空的项目数组。我认为该类别有很多供应商,所以我添加了很多。

public function supplierList() 
{
    return $this->hasMany('App\DB\Supplier\SupplierCategoryDetail', 'cat_id', 'id');        
}

我如何弄清楚它以获得随机类别。但在使用with() 后,结果为空。

$data['featured_category'] = Category::with('supplierList')->where('status','1')->inRandomOrder()->limit(3)->get();`

我对 laravel 和它的关系完全陌生。我在 laravel 中使用 eloquent 来做这件事。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    请参阅此文档: https://laravel.com/docs/5.6/eloquent-relationships

    你应该在两个相互关联的模型上编写关系函数。

    请这样做:

    Category.php

    public function supplierCategory()
        {
            return $this->hasMany('App\SupplierCategory');
        }
    

    Supplier.php

    public function supplierCategory()
        {
            return $this->hasMany('App\SupplierCategory');
        }
    

    SupplierCategory.php

    public function supplier()
        {
            return $this->belongsTo('App\Supplier');
        }
    
        public function category()
        {
            return $this->belongsTo('App\Category');
        }
    

    Controller.php

    $results = SupplierCategory::inRandomOrder()->limit(3)->get();
    
          return view('index', compact('results'));
    

    index.blade.php

    @foreach($results as $result)
             {{$result->supplier}}
             {{$result->category}}
          @endforeach
    

    【讨论】:

      【解决方案2】:

      由于您使用枢轴,因此可以实现“多对多”关系。在这种情况下,您想使用belongsToMany

      你的关系看起来像:

      return $this->belongsToMany(
          'App\DB\Supplier\SupplierCategoryDetail',
          'SupplierCategoryMappingTable', // or what the name is of the table
          'cat_id',
          'sup_id'
      );
      

      我也没有在您的类别表中看到status 列。看起来应该是is_featured

      如果不进行测试,我认为您的最终查询可能如下所示:

      Category::with('supplierList')
          ->where('is_featured', '1')
          ->inRandomOrder()
          ->limit(3)
          ->get();
      

      【讨论】:

        猜你喜欢
        • 2021-08-03
        • 2020-07-01
        • 2018-02-14
        • 2020-08-17
        • 1970-01-01
        • 1970-01-01
        • 2021-08-06
        • 2020-11-07
        • 2020-11-27
        相关资源
        最近更新 更多