即使该字段不受保护,我的编辑器也会显示错误,现在我想知道
model
是否是有效的列名称,或者它只是 PHP 调试工具/扩展中的一个错误。
我正在使用 VScode,并且我有这个 php 相关扩展:
我通过 DEVSENSE 禁用了 PHP,错误消失了,所以它可能是扩展中的错误?
错误信息:Member has protected visibility and is not accessible from the current context.PHP(PHP1416)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$products = Product::all();
$products = $products->map(function ($product) {
return [
'id' => $product->id,
'name' => $product->name,
'brand' => $product->brand,
'model' => $product->model,
'description' => $product->description,
'image_url' => $product->image_url,
'price' => $product->price,
'category_name' => $product->category->name ?? 'N/A',
'supplier_name' => $product->supplier->name ?? 'N/A',
];
});
return response()->json($products);
}
}
模型中的Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
public function category()
{
return $this->belongsTo(Category::class);
}
public function supplier()
{
return $this->belongsTo(Supplier::class);
}
}
这是我在迁移中创建表的方法
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->foreignId('category_id')->constrained('categories')->onDelete('restrict');
$table->foreignId('supplier_id')->constrained('suppliers')->onDelete('restrict');
$table->string('name');
$table->string('brand');
$table->string('model');
$table->string('description');
$table->string('image_url');
$table->decimal('price');
$table->timestamps();
});
DB::statement('ALTER TABLE products AUTO_INCREMENT = 100000;');
}
(和您一样,我没有注意到 PHP 或 MySQL 中存在任何问题,通过 DEVSENSE 禁用 PHP 可以让它消失。)