首页 > 解决方案 > 如何根据要求按条件在 laravel eloquent 中添加或删除属性

问题描述

我有许多帖子类型的帖子模型。我需要按帖子类型控制帖子属性。例如,我有 2 种帖子类型:

模型只发布一次。

后模型方案:

id
title
description
parent_id
type

请求song帖子类型时,如何singer自动将属性添加到响应数组或请求singer帖子类型添加属性时songs

我在使用方法的模型内部感到厌烦__construct()但不起作用:

public function __construct() {
    if($this->type == "song") {
        //$this->with = array_push($this->with, "singer");
        $this->appends = array_push($this->appends, 'singer');
    }
}

标签: laraveleloquent

解决方案


public function __construct() {
   parent::__construct()
    if($this->type == "song") {
        //$this->with = array_push($this->with, "singer");
        $this->appends = array_push($this->appends, 'singer');
    }
}

推荐阅读