【问题标题】:Laravel hasManyThrough() returning no resultsLaravel hasManyThrough() 不返回任何结果
【发布时间】:2018-02-01 08:32:28
【问题描述】:

我有 3 张桌子,我想通过另一个使用 eloquent 加入其中的 2 张桌子

ProductGroup table

--------------------------
| ProductGroupId | Name  |
-------------------------
| 1              | Test1 |
| 2              | Test2 |
--------------------------

ProductLine table
-------------------------------------------------
| ProductLineId | ProductGroupId | Name         |
------------------------------------------------|
| 1              | 1             | AnotherTest1 |
| 2              | 1             | AnotherTest2 |
-------------------------------------------------

ProductType table
----------------------------------------------
| ProductTypeId | ProductLineId | Name       |
---------------------------------------------|
| 1             | 1             | Something1 |
| 2             | 1             | Something2 |
----------------------------------------------

我想通过 ProductType 加入 ProductGroup

我尝试使用它作为我的 ProductGroup 模型(不确定我是否正确地完成了 hasManyThrough())

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductGroup extends Model
{
    protected $primaryKey = 'ProductGroupId';
    public $timestamps = false;

    public function producttype()
    {
        return $this->hasManyThrough('App\ProductGroup', 'App\ProductLine', 'ProductGroupId', 'ProductGroupId');
    }
}

我想从 ProductGroup 表中以特定 id 加入 2 个表,所以实际上在 SQL 中会是

SELECT * FROM ProductType pt
        INNER JOIN ProductLine pl ON 
            pt.ProductLineId = pl.ProductLineId
        INNER JOIN ProductGroup pg ON 
            pg.ProductGroupId = pl.ProductGroupId
    WHERE pg.ProductGroupId = 3

我试过了,但没有结果

我可以在查询生成器中执行此操作,但如果有帮助,我宁愿使用 eloquent

$test = ProductGroup::with('producttype')->whereHas('producttype', function ($query) {
    $query->where('ProductGroup.ProductGroupId', 3);
})->get();

【问题讨论】:

    标签: sql eloquent laravel-5.4


    【解决方案1】:

    改变

    public function producttype()
    {
        return $this->hasManyThrough('App\ProductGroup', 'App\ProductLine', 
        'ProductGroupId', 'ProductGroupId');
    }
    

    public function producttype()
    {
        return $this->hasManyThrough('App\ProductType', 'App\ProductLine', 'ProductGroupId', 'ProductLineId');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 2018-07-17
      • 2018-05-28
      • 2020-06-26
      • 1970-01-01
      • 2017-12-28
      • 2017-12-09
      相关资源
      最近更新 更多