【发布时间】:2021-11-19 18:58:26
【问题描述】:
在 laravel 中,我可以在我的产品模型中获取FirstNameAttribute 并更改值,但我正在创建此列“priceArray”,但我无法获取属性,因为第二个单词中的第一个字母是大写字母,模型找不到此列.
public function getPriceArrayAttribute($value)
{
return 'test';
}
它不起作用,无法获取“priceArray”列
这是我的迁移
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title')->nullable();
$table->string('price')->nullable();
$table->string('priceArray')->nullable();
$table->text('items')->nullable();
$table->enum('status',['active','inactive','unavailable'])->default('inactive');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
这是我的产品型号
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Class Products
* @package App\Models
* @property Variants Variants
*/
class Products extends Model
{
use HasFactory;
protected $guarded=[];
protected $changePrice=0;
public function Insert($data)
{
return self::create($data);
}
public function getPriceArrayAttribute($value)
{
return 'test';
}
public function getPriceAttribute($value)
{
return ceil($value);
}
}
getPriceAttribute 有效,但 getPriceArrayAttribute 无效
【问题讨论】:
-
这将作为
$model->price_array或$model->priceArray工作;您能否包含所有相关代码,包括您尝试使用它的位置?此外,如果您有price_array列,则需要将其命名为其他名称以防止歧义,例如getPriceArrayColAttribute,然后是$model->price_array_col或$model->priceArrayCol -
我在表中的列设置 priceArray,我需要在我的模型中调用 getPriceArrayAttribute 函数并更改所有行的值
-
@TimLewis 问题已编辑
-
是的,所以你有一个
priceArray列。当您调用$model->priceArray时,它会从数据库中返回值。当您拨打$model->price_array时,它应该是'test'。或者你可以按照我原来的评论,给他们唯一的名字。但是,您仍然没有包括如何使用此代码...根据设计,此函数在您调用它之前实际上并没有做任何事情。老实说,我只是不确定你想在这里做什么????
标签: laravel eloquent model getattribute