我的一对多关系不起作用,当我尝试在视图中调用它时,它会显示错误试图获取属性'senders_name'



我希望能够将相关表的值传递给我的视图,我正在使用一对多关系。此外,我正在尝试在不使用外键的情况下进行连接,我被告知将其用于mysql数据库是无效的,它可能会带来错误或什么都不做。我实际上测试了它,我指的是外键,它不起作用。

后模型:

namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Post extends Model
{
//Post model
protected $table = 'posts';
public function staff()
{
return $this->belongsTo('AppModelsStaff');
}
}

员工模式:

namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Staff extends Model
{
protected $table = 'staff';
public function posts()
{
return $this->hasMany('AppModelsPost');
}
}

创建posts表迁移:

<?php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
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 IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
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>

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');

您必须在代码中将AppModelsStaff替换为Staff::class

...
return $this->belongsTo(Staff::class);
...

相关内容

最新更新