表:优惠券
表shop_category:
优惠券模式:
use Model;
/**
* Model
*/
class Coupon extends Model
{
/**
* @var string The database table used by the model.
*/
public $table = 'coupons';
/**
* @var array Validation rules
*/
public $rules = [
];
public $belongsTo = [
'category' => ['ItScholarBd\Api\Models\Category','key' => 'id']
];
}
类别模式:
use Model;
use Lang;
/**
* Model
*/
class Category extends Model
{
public $implement = ['@RainLab.Translate.Behaviors.TranslatableModel'];
public $translatable = ['name'];
/**
* @var string The database table used by the model.
*/
public $table = 'shop_category';
/**
* @var array Validation rules
*/
public $rules = [
];
public $attachOne = [
'icon' => 'System\Models\File'
];
}
现在,我想得到以下类别的优惠券:
$records = \ItScholarBd\api\Models\Coupon::with(['category']);
但当我按如下方式打印记录时:
echo '<pre>';print_r($records->toArray()); exit;
它显示:
Array
(
[0] => Array
(
[id] => 4
[code] => FEAST50
[discount] => 2
[validity] => 2020-11-17 23:59:59
[min_order] => 40
[shop_category_id] => 1
[created_at] => 2020-11-07 17:13:40
[updated_at] => 2020-11-07 17:13:40
[category] =>
)
[1] => Array
(
[id] => 1
[code] => FEAST50
[discount] => 2
[validity] => 2020-11-17 23:59:59
[min_order] => 40
[shop_category_id] => 1
[created_at] => 2020-11-07 17:13:40
[updated_at] => 2020-11-07 17:13:40
[category] => Array
(
[id] => 1
[name] => Shopping
[created_at] => 2020-10-20 16:05:05
[updated_at] => 2020-10-20 16:05:05
)
)
)
为什么第一个元素的“类别”索引是空的,因为两行优惠券表是相同的?我正在努力寻找错误,但没有运气。有什么暗示吗?
发布于 2020-11-07 21:57:20
public function category(){
return $this->belongsTo(Category::class,'shop_category_id','id');
}
Hi in模型
public function coupon(){
return $this->hasMany(Coupon::class);
}
你可以称之为类别
$coupons = Coupon::with('category')->get();
https://stackoverflow.com/questions/64730949
复制相似问题