Laravel5 Eloquent 查询

Laravel5 Eloquent Query

我是 Laravel 的新手,遇到了一个查询。我有 ShopCustomer table,其中 it.There 中的 shop_id 和 customer_id 是 shop_id 的多个条目,其中有不同的 customer_id。它有多对多的关系。

我有一个 shop_id = 2。我想通过他们的名字找到客户 = 'Mat'。我已经用 JOIN 子句尝试了我的代码。我希望将以下查询转换为 Eloquent 查询构建器并希望使用预加载。

$customers = \DB::table('shop_cust')
            ->join('customers', 'customers.customer_id', '=', 'shop_cust.customer_id')
            ->select('shop_cust.total_amount', 'customers.*')
            ->where('customers.name', 'LIKE', 'Mat')
            ->where('shop_cust.shop_id', '=', '2')
            ->get();

dd($customers);

这是我试过的。

$customers = ShopCust::with(['customer' => function ($query)
 use ($customerName) {
      $query->where('name', 'LIKE', '%' . $customerName . '%');
 }])->where('shop_id','=', $shopId)->get();

ShopCustomer 模型

class ShopCustomer Eloquent {

    public function customers()
    {
    return $this->hasMany('Customer','customer_id','customer_id');
    }


    public function shops()
    {
    return $this->hasMany('Shop','shop_id','shop_id');
    }

}

客户模型

class Customer Eloquent {

    public function customer_shop()
    {
    return $this->belongToMany('ShopCustomer','customer_id','customer_id');
    }

}

店铺模型

class Shop Eloquent {

        public function shop_customer()
        {
        return $this->belongToMany('ShopCustomer','shop_id','shop_id');
        }

    }

您的查询

$customers = ShopCustomer::
    ->with(arra('customer' => function($q) use ($customerName){
                                        $query->where('name', 'LIKE', '%' . $customerName . '%');
                                    }))
    ->where('shop_id','=', $shopId)->get();

您所描述的是 Shop 和 Customer 之间的多对多关系。您的 shop_cust table 只是关系的支点 table。除非您对 shop_cust 有一些特殊的功能,否则不需要为其定义模型。

class Shop extends Model {
    public function customers() {
        return $this->belongToMany('Customer', 'shop_cust');
    }
}

class Customer extends Model {
    public function shops() {
        return $this->belongToMany('Shop', 'shop_cust');
    }
}

使用此定义,您的代码将如下所示:

$shop = Shop::find(2);
$customers = $shop->customers()->where('name', 'LIKE', 'Mat');

这里没有真正需要预先加载,因为您只是在寻找一家特定商店的顾客。

编辑

如果您想要访问数据透视 table 上的额外字段,您也可以这样做。首先,您使用关系上的 withPivot() 方法添加对额外字段的访问:

class Shop extends Model {
    public function customers() {
        return $this->belongToMany('Customer', 'shop_cust')->withPivot('foo', 'bar');
    }
}

class Customer extends Model {
    public function shops() {
        return $this->belongToMany('Shop', 'shop_cust')->withPivot('foo', 'bar');
    }
}

现在,您可以通过数据透视模型属性访问数据:

foreach ($customers as $customer) {
    echo $customer->pivot->foo;
    echo $customer->pivot->bar;
}

使用数据透视表的文档 tables here.