【问题标题】:Use foreign key id to get a foreign table name使用外键 id 获取外表名
【发布时间】: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-&gt;categories_id-&gt;name

【问题讨论】:

    标签: php laravel eloquent foreign-keys


    【解决方案1】:

    根据您的模型,您必须使用:

    // get all estates for the example
    $estates = Estate::get();
    
    foreach ($estates as $estate) {
        // use the name of the relation to get your category - first
        dump($etate->category[0]->name);
    
        // or to get all categories
        foreach ($etate->category as $category) {
            dump($category->name);
        }
    }
    

    【讨论】:

    • 适用于:@foreach($EstateList as $EstateList) &lt;th scope="row"&gt;{{$EstateList-&gt;category[0]-&gt;name}}&lt;/th&gt; @endforeach
    【解决方案2】:

    我相信这会起作用..如果我错了,请纠正我

    Estate::with('category')->get();
    

    它将带回所有庄园,每个庄园都附有其类别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      相关资源
      最近更新 更多