php - 为什么 Laravel 无法创建模型关系?
问题描述
我正在尝试在 laravel 中的模型之间建立关系,但由于某种原因它似乎失败了。
class User extends Authenticatable
{
use HasFactory, Notifiable;
protected $table = 'users';
protected $fillable = [
'name',
'email',
'password',
'userType'
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
//classes created by user;
public function classes() {
return $this->hasMany(userOwnedClass::class, 'ownerId');
}
}
class userOwnedClass extends Model {
protected $table = 'classes';
protected $fillable = ['name', 'archived', 'ownerId'];
public $timestamps = false;
public function owner() {
return $this->belongsTo(User::class, 'ownerId');
}
}
的数据库结构users
如下所示:
class Users extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id('id');
$table->string('name');
$table->string('email')->unique();
$table->enum('userType', ['student', 'teacher']);
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
类的数据库结构如下所示:
class Classes extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('classes', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->boolean('archived')->default(0);
$table->integer('ownerId')->unsigned();
$table->foreign('ownerId')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('classes');
}
}
每当我尝试owner()
在 的实例上对方法进行分类时userOwnedClass
,我都会收到一个Illuminate\Database\Eloquent\Relations\BelongsTo
对象而不是 User 的实例。任何人都可以识别错误吗?
解决方案
您应该将owner
其称为属性而不是方法。
$userOwnedClass->owner;
当你调用owner()
方法时,你会得到一个 eloquent 关系的实例来对该模型执行额外的查询。
如果调用函数 owner(),可以通过以下方式获取所有者的 id
$userOwnedClass->owner()->id;
推荐阅读
- python - 无法使用 Google Cloud Scheduler 调用 Google Cloud Function
- arrays - 在 ruby 中打印 .txt 时遇到问题,ruby 文件处理
- swift - Swift 协议的可变性
- java - JPA 存储库抛出空指针异常
- java - NoClassDefFoundError com/android/resources/ResourceFolderType
- node.js - 如何从命令行设置 Firebase 自定义声明?
- jquery - 如何禁用除剑道网格中的所有列之外的所有列的编辑?
- python - 如果它们重叠,如何比较pandas / python中的两行
- c# - 无法从 Windows 窗体上的图片框中删除形状?
- c# - 通过 post 请求接受 Pdf 并在 c# .net core 中传递给 itext7 pdfreader