您可以尝试为您的问题提供解决方案。
<?php
//You can see here for all table migration files
// For Client Table
Schema::create('client', function (Blueprint $table) {
$table->increments('id');
$table->string("client_name");
$table->timestamps();
// You can add your more fields and you can change field name also
});
// For Supplier Table
Schema::create('supplier', function (Blueprint $table) {
$table->increments('id');
$table->string("supplier_name");
$table->timestamps();
// You can add your more fields and you can change field name also
});
// For Invoice Table
Schema::create('invoices', function (Blueprint $table) {
$table->increments('id');
$table->morphs('invoice');
$table->timestamps();
// You can add your more fields and you can change field name also
});
//Note:
$table→morphs('invoice') would automatically create two columns using the text passed to it + “able”. So it will result in invoiceable_id and invoiceable_type.
?>
这里是 morphTo relationship 的模型
客户端模型: Client.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
/**
* Get all of the Client's invoices.
*/
public function invoices()
{
return $this->morphMany(Invoices::class, 'invoiceable');
}
}
?>
供应商模型: Supplier.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Supplier extends Model
{
/**
* Get all of the Supplier's invoices.
*/
public function invoices()
{
return $this->morphMany(Invoices::class, 'invoiceable');
}
}
?>
发票模型: Invoices.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Invoices extends Model
{
/**
* Get all of the owning invoiceable models.
*/
public function invoiceable()
{
return $this->morphTo();
}
}
?>
现在您可以使用多态关系使用客户和供应商检索记录。
使用客户端模型检索记录。
$client = Client::find(1);
dd($client->invoices);
使用供应商模型检索记录。
$supplier = Supplier::find(1);
dd($supplier->invoices);
您也可以检索记录
$client = Client::find(1);
foreach ($client->invoices as $invoice) {
<a href="{{ route('view-client', ['id' => $invoice->id]) }}">
<b>{{ $invoice->client_name }}</b>
</a>
}