我希望能夠將相關表的值傳遞給我的視圖,我正在使用一對多關系。我也試圖在不使用外鍵的情況下進行連接,我被告知將它用于 mysql 資料庫效率不高,它可能會引發錯誤或不做任何事情。我實際上測驗了它,我的意思是外鍵,它不起作用。
崗位型號:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//Post model
protected $table = 'posts';
public function staff()
{
return $this->belongsTo('App\Models\Staff');
}
}
員工模型:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Staff extends Model
{
protected $table = 'staff';
public function posts()
{
return $this->hasMany('App\Models\Post');
}
}
創建posts表遷移:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{ //my post table
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('name');
$table->string('phone_number');
$table->mediumText('fault_explained');
$table->string('repair_type');
$table->string('repair_part');
$table->integer('repair_total');
$table->mediumtext('justify');
$table->string('vendor_name');
$table->string('vendor_number');
$table->string('status_option');
$table->integer('status_value');
$table->string('vehicle_name');
$table->string('vehicle_number');
$table->integer('staff_id')->nullable()->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
創建staff表遷移:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateStaffTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{ //Staff table
Schema::create('staff', function (Blueprint $table) {
$table->increments('id');
$table->string('senders_name');
$table->string('senders_number');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('staff');
}
}
看法:
<div class="content-wrapper">
<main class="st_viewport">
<div class="border bg-warning">
<div style="margin-left:14px; margin-top:5px;">
<span class="h2 wrapper " > <em><b>SUBJECT:</b> {{ $posts->title }}</span></em>
</div>
<div class="" style="margin-left:14px; margin-bottom:5px;">
<em><b>Sent on</b> {{ $posts->created_at }}</em> {{ $posts->staff->senders_name}}
</div>
uj5u.com熱心網友回復:
在Post您應該使用的模型中 -
public function staff()
{
return $this->belongsTo(Staff::class);
}
在Staff您應該使用的模型中 -
public function posts()
{
return $this->hasMany(Post::class);
}
在 CreatePostsTable 遷移中,您需要再添加一行 -
$table->foreign('staff_id')->references('id')->on('staff');
uj5u.com熱心網友回復:
您必須更換App\Models\Staff與Staff::class在你的代碼。
...
return $this->belongsTo(Staff::class);
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407030.html
標籤:
