【发布时间】:2020-06-14 03:30:16
【问题描述】:
我有一些表,所有 estate 都有一个 category_id,我放了一个外键来建立关系,但现在不起作用,我该如何列出我的具有相同类别名称的庄园
类别模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
protected $fillable = ['name'];
public function estate()
{
return $this->belongsTo('App\Estate');
}
}
房地产模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Estate extends Model
{
protected $table = 'estates';
protected $fillable = ['categories_id'];
public function category()
{
return $this->hasMany('App\Category');
}
}
创建庄园表
Schema::create('estates', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->string('name');
$table->string('estate_photo')->nullable(true);
$table->double('value');
$table->integer('label_id');
});
创建类别表
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
向房地产添加类别外键
Schema::table('estates', function (Blueprint $table) {
$table->unsignedBigInteger('categories_id');
$table->unsignedBigInteger('sub_categories_id');
$table->foreign('categories_id')->references('id')->on('categories');
$table->foreign('sub_categories_id')->references('id')->on('sub_categories');
});
我的对象没有外键数据来获取$object->categories_id->name
【问题讨论】:
标签: php laravel eloquent foreign-keys