Eloquent - 如何匹配单个ID的表之间的数据

Eloquent - How to match data between tables of a single ID

有多个 table 具有相互关联的数据,我正在尝试使用 Laravel 在视图中显示该数据。

我一定对 Laravel 如何运行它的查询感到困惑,我需要帮助来排序如何做,PHP&SQL 中的左连接。

我的资产模型:

public function category(){
        return $this->hasOne(Category::class);
    }

我的分类模型:

public function asset()
    {
        return $this->belongsTo(Asset::class);
    }

我的国家模式:

public function country()
    {
        return $this->belongsTo(Asset::class);
    }

还有我的 AssetsController:

public function asset($id)
    {

        $asset = Asset::find($id);

        return view('admin.assets.asset')->with('assets', $asset);

    }

路由器:

Route::get('/admin/assets/asset/{id}', [
        'uses' => 'AssetsController@asset',
        'as' => 'assets.asset'
        //Show the Asset
    ]);

和视图:

<p><strong>Price:</strong>{{$assets->price}} €</p>
<p><strong>Description:</strong>{{$assets->description}}</p>
<p><strong>Country:</strong>{{$assets->country}}</p>
<p><strong>Category:</strong>{{$assets->name}}</p>

所以在 'asset.blade.php' 中,我从之前的 index.blade.php 中获取 ID,其中包含所有资产的列表。我想通过 ID 获取显示类别名称和国家名称的资产页面,而不是属于资产的 ID table。

所以它应该回显类似 $assets->country->country_name$assets->category->name

dd($asset);

编辑:关于迁移的更多信息

categories_table迁移

public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('url');
            $table->timestamps();
        });
    }

assets_table迁移:

public function up()
    {
        Schema::create('assets', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->double('price',15,2);
            $table->mediumText('description');
            $table->integer('country');
            $table->integer('category');
            $table->integer('subcategory');
            $table->integer('subsubcategory');
            $table->integer('broker');
            $table->string('featured');
            $table->string('slug');
            $table->timestamps();
        });
}

成功了。

class Category
{
    public function asset()
    {
        return $this->hasMany(Asset::class);
    }
}
class Asset
{
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}
use App\Asset;
use App\Category;
use App\Country;
use App\Subcategory;
use Illuminate\Http\Request;

class AssetController extends Controller
{
    public function asset($id)
    {
        $asset = Asset::find($id);

        return view('admin.assets.asset')
            ->with('asset', $asset)
            ->with('category', Category::all())
            ->with('subcategory', Subcategory::all())
            ->with('country', Country::all());
    }
}

其他模型与 Asset 模型具有相同的关系,反之亦然。

观点:

<p><strong>Category:</strong>{{$asset->category->name}}</p>
<p><strong>Sub-Category:</strong>{{$asset->subcategory->name}}</p>

它现在显示与相应表的 ID 匹配的名称。