首页 > 解决方案 > Laravel hasManyThrough 什么都不返回

问题描述

产品:

-----------------------
|id | name  | seller_id  |
-----------------------
| 1 | bmw   |    1     |
-----------------------
| 2 | benz  |    1     |
-----------------------
| 2 | reno  |    2     |
-----------------------

买:

------------------------------
|id | product_id  | buyer_id  |
------------------------------
| 1 |     1     |      1      |
------------------------------
| 2 |     1     |      2      |
------------------------------
| 3 |     2     |      22     |
------------------------------

买方:

------------------------------
|id | name     |       email  |
------------------------------
| 1 |     john     |      @   |
------------------------------
| 2 |     mike     |      @   |
------------------------------
| 3 |     dave     |      @  |
------------------------------

解释:

卖家productsproducts桌,买家购买产品后入buy桌。有buyer表格也有seller表格,我想做的是,将这些buyer数据显示给seller谁购买了卖家产品。

考虑一下,一个卖家有seller_id1,制造产品,一些买家购买了他/她的产品,对吗?现在我想向购买了你们产品的卖家展示。john 和 mike 购买了 bmw,现在 id 为 1 的卖家应该在每个产品下看到 mike 和 john 的电子邮件等。

我尝试了什么:

产品控制器.php:

$pro = Product::where('seller_id', $seller->id)->where('deleted', 0)->with('buyer')->get();

产品.php:

function buyer()
    {
        //return $this->belongsTo('App\Buy', 'id'); // this just show me buyer_id
        return $this->hasManyThrough('App\Buyer', 'App\Buy', 'id', 'id', 'product_id', 'buyer_id');
    }

这返回我的产品但buyer为空,我是 laravel 的新手,"buyer": []我不知道哪个localKey,,或与哪个表相关。所以知道我做错了什么吗?firstKeysecondKeysecondLocalKey

- 编辑 -

public function userproducts()
{
    $seller = Auth::seller();
    $pro = Product::where('seller_id', $seller->id)->where('deleted', 0)->with('buyer')->get();

    return response()->json($pro, 200 );
}

标签: phplaravel

解决方案


你建立了错误的关系。正如您所解释的,您的产品有很多买家,买家可以购买很多产品。

所以,这将是一个多对多的关系。

尝试建立如下关系,然后检查它是否适合您。

Product.php模型

function buyers(){
     return $this->belongsToMany('App\Buyer','Buy_table_name','product_id','buyer_id');
}

Buyer.php模型中

function products(){   
   return $this->belongsToMany('App\Product','Buy_table_name','buyer_id','product_id');
}

现在,在控制器文件中使用这个查询。

$pro = Product::where('seller_id', $seller->id)->where('deleted', 0)->with('buyers')->get();

推荐阅读