两表关联 商品表,关联库存表, 现 库存表 反向关联商品表,查询商品名字,但会查询出很多为空的数据
未使用查询条件结果如图
模型关联代码如下:
class GoodsSpec extends Model
{
protected $guarded = [];
protected $table = 'g_specification';
// 商品模型关联商品表
public function goods(){
return $this->belongsTo(Goods::class,'g_product_id','product_id');
}
}
查询代码如下
// 商品库存日志
class GoodsStockLogController extends Controller
{
use LayuiTableController;
public function lists(Request $request){
DB::connection()->enableQueryLog();#开启执行日志
$dd = GoodsSpec::with(['goods' => function($query) use($request){
if ($request->has('search.name')){
$query->where('name', $request->search['name'] )->select('name','product_id');
}else{
$query->select('name','product_id');
}
}])
->offset($this->params($request))
->limit($request->limit)
->get()->toArray();
// dd(DB::getQueryLog());
// dd($dd);
$count = GoodsSpec::with(['goods' => function($query) use($request){
if ($request->has('search.name')){
$query->where('name', $request->search['name'] );
}
}])->count();
return asTableData($dd,$count);
}
}