Я использую Laravel 5.7 с laravelcollective / html для форм.
У меня есть эти 3 таблицы (исключая временные метки):
Поставщики:
|id|name|website|
Продукты:
|id|name|description|product_category_id|supplier_id|sales_price|buy_price|instock|discontinued|
Категории продуктов:
|id|name|
Я пытаюсь отобразить название категории продукта и поставщика в режиме редактирования, но не могу это сделать.
Я знаю, что могу просто получить доступ к идентификатору, используя $product->product_category_id
, но мне также нужно имя.Идентификатор должен храниться в базе данных, а имя должно отображаться в режиме редактирования.
Я пробовал:
Создание красноречивых отношений в модели продуктоввот так:
public function category()
{
return $this->hasOne('App\ProductCategory');
}
Затем я использовал $product->category()
, он вернул эту ошибку:
Объект класса Illuminate \ Database \ Eloquent \ Relations \ HasOne не может быть преобразован встрока
Я также пытался $product->category()->name
, он вернул эту ошибку:
Неопределенное свойство: Illuminate \ Database \ Eloquent \ Relations \ HasOne :: $ name
Что мне здесь не хватает?
Соответствующий код:
Мое представление редактирования:
<div class="row">
<div class="col-sm-12">
<div class="box box-danger">
<div class="box-header with-border">
<h3 class="box-title">Edit product {{$product->name}}</h3>
</div>
<div class="box-body">
{!! Form::open(['action' => ['ProductsController@update', $product->id], 'method' => 'post']) !!}
<div class="row">
<div class="col-sm-12">
<div class="form-group">
{{ Form::label('name', 'Product name') }}
{{ Form::text('name', $product->name, ['class' => 'form-control', 'placeholder' => 'Product name']) }}
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
{{Form::label('description', 'Product description')}}
{{Form::textarea('description', $product->description, ['id' => 'ckeditor', 'class' => 'form-control', 'style' => 'resize: vertical', 'placeholder' => 'Product description'])}}
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
{{Form::label('product_category_id', 'Product category')}}
{{Form::select('product_category_id', $categories->pluck('name', 'id'), /* here is where it should be */, ['id' => 'select2', 'class' => 'form-control select2', 'placeholder' => 'Product category'])}}
<p>Is the category you're looking for not in this list? Create it <a target="_blank" href="/product-categories/create">here</a>.</p>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
{{Form::label('supplier_id', 'Supplier')}}
{{Form::select('supplier_id', $suppliers->pluck('name', 'id'), null, ['id' => 'select2', 'class' => 'form-control select2', 'placeholder' => 'Supplier'])}}
<p>Is the supplier you're looking for not in this list? Add them <a target="_blank" href="/suppliers/create">here</a>.</p>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
{{Form::label('sales_price', 'Sales price')}}
{{Form::number('sales_price', $product->sales_price, ['class' => 'form-control', 'placeholder' => 'Sales price'])}}
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
{{Form::label('buy_price', 'Buy-in price')}}
{{Form::number('buy_price', $product->buy_price, ['class' => 'form-control', 'placeholder' => 'Buy-in price'])}}
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
{{Form::label('instock', 'In stock')}}
{{Form::select('instock', [0 => 'No', 1 => 'Yes'], null, ['id' => 'select2', 'class' => 'form-control select2', 'placeholder' => 'In stock'])}}
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
{{Form::label('discontinued', 'Discontinued')}}
{{Form::select('discontinued', [0 => 'No', 1 => 'Yes'], null, ['id' => 'select2', 'class' => 'form-control select2', 'placeholder' => 'Discontinued'])}}
</div>
</div>
</div>
{{ Form::hidden('_method', 'PUT') }}
{{ Form::submit('Save changes', ['class' => 'pull-right btn btn-default']) }}
{!! Form::close() !!}
</div>
</div>
</div>
</div>
Миграция таблицы продуктов
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->mediumText('description');
$table->integer('product_category_id')->unsigned();
$table->integer('supplier_id')->unsigned();
$table->decimal('sales_price', 8, 2);
$table->decimal('buy_price', 8, 2);
$table->boolean('instock');
$table->boolean('discontinued');
$table->foreign('product_category_id')->references('id')->on('product_categories')->onDelete('cascade');
$table->foreign('supplier_id')->references('id')->on('suppliers')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
Таблица поставщиков
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSuppliersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('suppliers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('website');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('suppliers');
}
}
Таблица категорий продуктов
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('product_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('product_categories');
}
}