首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在laravel中雄辩的关系不适用于多行。

在laravel中雄辩的关系不适用于多行。
EN

Stack Overflow用户
提问于 2020-11-07 18:18:10
回答 1查看 65关注 0票数 0

表:优惠券

shop_category:

优惠券模式:

代码语言:javascript
运行
复制
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']
    ];

}

类别模式:

代码语言:javascript
运行
复制
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'
    ];
}

现在,我想得到以下类别的优惠券:

代码语言:javascript
运行
复制
 $records    =   \ItScholarBd\api\Models\Coupon::with(['category']);

但当我按如下方式打印记录时:

代码语言:javascript
运行
复制
echo '<pre>';print_r($records->toArray()); exit;

它显示:

代码语言:javascript
运行
复制
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
                )

        )

)

为什么第一个元素的“类别”索引是空的,因为两行优惠券表是相同的?我正在努力寻找错误,但没有运气。有什么暗示吗?

EN

回答 1

Stack Overflow用户

发布于 2020-11-07 21:57:20

代码语言:javascript
运行
复制
public function category(){

        return $this->belongsTo(Category::class,'shop_category_id','id');

    }

Hi in模型

代码语言:javascript
运行
复制
public function coupon(){

        return $this->hasMany(Coupon::class);

    }

你可以称之为类别

代码语言:javascript
运行
复制
$coupons = Coupon::with('category')->get();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64730949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档