【发布时间】:2019-11-25 07:39:48
【问题描述】:
我正在开发 laravel v5.8 项目。我在建立一对多关系时遇到了一些问题。
我有两个表,一个是提供一些服务和其他表服务的用户。我想在它们之间建立一对多的关系。 因为用户必须有许多服务。 for service 必须属于 To on 用户。 我的代码:
用户.php
public function services()
{
return $this->hasMany(Service::class);
}
服务.php
public function user()
{
return $this->belongsTo(User::class);
}
控制器.php
public function index()
{
//
return view('vendor.services',['services'=>Service::with("user")->get()]);
}
刀片文件
@foreach ($services as $service )
<tr>
<td>{{$service->name}}</td>
<td>{{$service->user_id->name}}</td>
</tr>
@endforeach
迁移 1.用户
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
2.服务
Schema::create('services', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string("short_desc", 250);
$table->string("long_desc", 1500);
$table->double("price", 10);
$table->bigInteger('type_id')->unsigned();
$table->foreign('type_id')->references('id')->on('types');
$table->string("img");
$table->bigInteger("city_id")->unsigned()->nullable();
$table->foreign('city_id')->references('id')->on('cities');
$table->bigInteger("region_id")->unsigned()->nullable();
$table->foreign('region_id')->references('id')->on('regions');
$table->bigInteger("user_id")->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
错误: 试图获取非对象的属性“名称”(查看:/home/nazeeh/Desktop/petVet/resources/views/vendor/services.blade.php)
【问题讨论】:
-
“我有一些问题” - 那么究竟是什么问题?你有任何错误吗?
-
是的,但我按照以下答案修复了它。谢谢。
标签: laravel laravel-5 eloquent