尝试在 Laravel 中使用 belongsTo 但它不起作用

Tried to using belongsTo in Laravel but its not working

我使用 Laravel 6.2

我想做一个库存数据库系统。我有 2 个模态 ProdukStock。 在那种情况下,我想从 ProdukTable 输入数据 p_namesku 并使用 Eloquent ORM[=41 将其放入 StockTable =].

我尝试使用 belongsTo(),

Here's my modal Produk code

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Produk extends Model
{
    public $table = 'produk';
    protected $primaryKey = 'pid';
    protected $fillable = [
        'pid',
        'p_nama',
        'sku',
        'p_harga',
        'status'
    ];
}

Here's my modal Stock code

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Stock extends Model
{
    public $table = 'stock';
    protected $primaryKey = 'sid';
    protected $fillable = [
        'sid',
        'p_nama',
        'sku',
        'p_stock_min',
        'p_stock',
        'status'
    ];

    public function produk()
    {
        return $this->belongsTo('App\Produk', 'pid');
    }
}

My StockController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Stock;
use App\Produk;
use RealRashid\SweetAlert\Facades\Alert;

class StockController extends Controller
{
    public function index()
    {
        $datas = Stock::paginate(5); // 5 record per pages
        return view('stock.list', compact('datas'));

        // $datas  = Stock::all();
        // return $datas;
    }

    . . . .
}

My View stock.blade

            <div class="body">
                <div>
                    <a href="{{ route('stock.create')}}" class="btn btn-success btn-round" data-type="confirm"> <i class="zmdi zmdi-account-add"></i>&nbsp;Tambah Stock</a>
                    <a style="margin: 2px;" href="{{ route('stock.index')}}" class="btn btn-primary btn-sm"><i class="zmdi zmdi-refresh"></i></a>
                </div>
                <div class="col-sm-12">
                    @if(session()->get('success'))
                        <div class="alert alert-success">
                            {{ session()->get('success') }}
                        </div>
                    @endif
                </div>
                <table class="table table-bordered table-striped table-hover dataTable js-exportable">
                    <thead>
                        <tr>
                            <th class="text-center" style="width:5%">#</th>
                            <th class="text-center" style="width:25%">Nama Produk</th>
                            <th class="text-center" style="width:10%">SKU Produk</th>
                            <th class="text-center" style="width:8%">Min. Stock</th>
                            <th class="text-center" style="width:8%">Stock</th>
                            <th class="text-center" style="width:10%">Status</th>
                            <th class="text-center" style="width:10%">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        @if(!empty($datas) && $datas->count())
                            @foreach($datas as $data)
                            <tr>
                                <th class="text-center">{{ $loop->iteration }}</th>
                                <td>{{ $data->produk }}</td>
                                <td>{{ $data->p_nama }}</td>
                                <td>{{ $data->p_stock_min }}<code> pcs</code></td>
                                <td>{{ $data->p_stock }}<code> pcs</code></td>
                                <td class="text-center">{{ $data->status }}</td>
                                <td class="text-center">
                                    <a href="{{ route('stock.edit', $data->sid)}}" title="Ubah" class="btn btn-warning btn-icon btn-icon-mini btn-round"> <i class="zmdi zmdi-edit"></i></span></a>&nbsp;
                                    <a href="{{ route('stock.delete', $data->sid)}}" title="Hapus" class="btn btn-danger btn-icon btn-icon-mini btn-round" data-type="success"> <i class="zmdi zmdi-delete"></i></span></a>
                                </td>
                            </tr>
                            @endforeach
                        @else
                            <tr>
                                <td colspan="8">Data tidak ditemukan! Silahkan buat data Stock terlebih dahulu.</td>
                            </tr>
                        @endif
                    </tbody>
                </table>
                {!! $datas->links() !!}
            </div>

Migration Stock

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateStocksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('stock', function (Blueprint $table) {
            $table->bigIncrements('sid');
            $table->bigInteger('produk_id')->unsigned();
            $table->string('p_nama');
            $table->string('sku');
            $table->integer('p_stock_min');
            $table->integer('p_stock')->nullable();
            $table->string('status');
            $table->timestamps();
        });

        Schema::table('stock', function (Blueprint $table) {

            $table->foreign('produk_id')->references('pid')->on('produk')
            ->onDelete('cascade')->onUpdate('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('stock');
    }
}

Response when i add data direct from PMA

[{"sid":1,"produk_id":6,"p_nama":"kopi1","sku":"12345678","p_stock_min":20,"p_stock":800,"status":"Aktif","created_at":"2020-11-24 16:37:16","updated_at":"2020-11-24 16:37:16"},
{"sid":2,"produk_id":7,"p_nama":"kopi2","sku":"87654321","p_stock_min":20,"p_stock":600,"status":"Aktif","created_at":"2020-11-24 16:37:16","updated_at":"2020-11-24 16:37:16"}]

我不知道我的错误在哪里? 只想使用 select 形式将数据 p_produk 添加到股票 table 中,当我 select 它 sku 数据将生成与 table产品.

在您的 Stock 模型中,您应该将外键放在 belongsTo 关系中。像这样编辑方法:

  public function produk()
    {
        return $this->belongsTo('App\Produk', 'produk_id');
    }

因为您没有在

上命名您的列

如果你想像这样使用这个命名,你必须自己定义它:

 public function produk()
    {
        return $this->belongsTo('App\Produk', 'pid' , 'id');
    }

as belongsTo 连续取 $relatedModel , $foreignKey , $ownerKey

使用 Laravel 约定,关系产品应定义为

public function produk()
{
    return $this->belongsTo(Produk::class, 'produk_id', 'pid');
}

根据用户在显示 $produk->[=25 的 select 选项 selected 动态更改 create.blade.php 只读输入中的天空值=]:

为 sku

的只读输入提供一个 id
<div class="form-group">
    <label for="sku">SKU:</label>
    <input type="text" class="form-control  form-control-lg" name="sku" id="skuSelected" readonly/>
</div>

跟踪选项 selected in select control

<select class="form-control select2" name="p_name" onChange="setSku(this);">
    @foreach($produks as $produk)
        <option value="{{ $produk->pid }}">{{ $produk->p_nama }}</option>
    @endforeach
</select>

通过 javascript

处理 selection 的变化
<script>
 function setSku(sel) {
    const sku = sel.options[sel.selectedIndex].text;
    document.getElementById('skuSelected').value = sku;
 }
</script>