加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – Laravel 5:如何使用Eloquent对数据透视表进行连接查询?

发布时间:2020-12-14 19:35:59 所属栏目:大数据 来源:网络整理
导读:我的Laravel应用程序中有2个表,即客户和商店.客户可以属于许多商店,商店可以拥有许多客户.它们之间有一个数据透视表来存储这种关系. 问题是,如何使用Eloquent提取给定商店的客户列表?可能吗?我目前能够使用Laravel的Query Builder提取它.这是我的代码: |
我的Laravel应用程序中有2个表,即客户和商店.客户可以属于许多商店,商店可以拥有许多客户.它们之间有一个数据透视表来存储这种关系.

问题是,如何使用Eloquent提取给定商店的客户列表?可能吗?我目前能够使用Laravel的Query Builder提取它.这是我的代码:

| customers | stores      | customer_store |
-------------------------------------------
| id        | id          | customer_id    |
| name      | name        | store_id       |
| created_at| created_at  | created_at     |
| updated_at| updated_at  | updated_at     |

客户模型:

public function stores(){
        return $this->belongsToMany(Store::class)
            ->withPivot('customer_store','store_id')
            ->withTimestamps();
    }

商店型号:

public function customers(){
        return $this->belongsToMany(Customer::class)
            ->withPivot('customer_store','customer_id')
            ->withTimestamps();
    }

数据库查询(使用查询生成器):

$customer = DB::select(SELECT customers.id,customers.name,customers.phone,customers.email,customers.location FROM customers LEFT JOIN customer_store on customers.id = customer_store.customer_id WHERE customer_store.store_id = $storeID);

解决方法

试试这个:

public function result(Request $request) {

    $storeId = $request->get('storeId');

    $customers = Customer::whereHas('stores',function($query) use($storeId) {
        $query->where('stores.id',$storeId);
    })->get();

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读