版权声明:廖圣平博客,未经博主允许不得转载。企鹅:1194008361 https://blog.csdn.net/qq_22823581/article/details/85259903
比如一个商品有多个sku
hasMany
模型
<?php
namespace App\Models;
class Goods extends BaseModel
{
public function getProduct(){
return $this->hasMany('App\Models\Products','goods_code','code');
}
}
调用:
Goods::with('getProduct')->where('code',$goods_id)->get();
{
"code": 200,
"message": "成功",
"data": [
{
"id": "553",
"code": "2017112322212452505251",
"get_product": [
{
"id": "5551",
"goods_code": "2017112322212452505251",
},
{
"id": "5552",
"goods_code": "2017112322212452505251",
}
]
}
]
}
从返回的json中可以看出,一个goods中,包含了两个product信息。
一个sku属于一个goods
所以用:
belongsTo
product 模型中:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Products extends Model
{
public function goods(){
return $this->belongsTo('App\Models\Goods','goods_code','code');
}
}
使用:
public function getProductByGoods_id($product_id=''){
return Goods::with('getProduct')->where('code',$product_id)->get();
}
输出:
{
"code": 200,
"message": "成功",
"data": [
{
"id": "5555",
"goods_code": "2017112322212452505251",
"goods": {
"id": "553",
"code": "2017112322212452505251",
}
}
]
}
从json中可以看出,一个sku对应一个goods 信息。
多对多关系 belongsToMany
中间有个表做映射关系。
比如一个商品对应不同的配送区域模板, 中间表为: godos_area_map ,存的数据为:goods_id ,还有area_id
在Goods model中编写:
public function ShipArea(){
return $this->belongsToMany('App\Models\ShipArea', 'goods_shiparea_map', 'goods_id', 'ship_area_id');
}
调用
<?php
namespace App\Http\Repository\Services;
use App\Models\Goods;
class ShipAreaRepository
{
/**
* 根据goodsid 获取不配送区域数据
*
* @param string $goods_id
*
* @return array
*/
public function getAreaInfoByGoodsId($goods_id=''){
return Goods::with('ShipArea')->where('id',$goods_id)->get();
}
}