雄辩 - 如何在单个 ID 的表之间匹配数据



有多个表,其中包含彼此相关的数据,我正在尝试使用 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);
}

和我的资产控制者:

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中获取id.php该索引具有所有资产的列表。我想通过 ID(一个显示类别名称和国家/地区名称的资产页面(而不是属于 Asset 表的 ID 获取。

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

日($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 AppAsset;
use AppCategory;
use AppCountry;
use AppSubcategory;
use IlluminateHttpRequest;
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 匹配的名称。

最新更新