在 Laravel 中,我有 Orders 模型,其中每个订单只属于一个用户, 我想在获取订单时只返回用户名和订单 ID,所以在我的 OrdersController 中我有这个功能 在我的 OrderResource 我有 我收到一条错误消息,指出Property [user] does ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
我试图建立一个页面,用户可以在其中添加关于他自己的描述,例如,他或她所从事的兴趣是什么,因此我与用户建立了单独的表,因此有一个USER表和PROFILE表,两个表的外观
用户表
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
资料表
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('email')->unique();
$table->string('firstname');
$table->string('lastname');
$table->integer('age');
$table->integer('birthdate');
$table->text('bio');
$table->timestamps();
});
}
因此在矿山模型中,我为配置文件和用户建立了关系,在laravel和hasone()中使用belognsto()函数,该模型的外观
user.php的
public function profile()
{
return $this->hasOne(Profile::class);
}
profile.php
public function user()
{
return $this->belongsTo(User::class);
}
但是当我尝试将其添加到刀片时出现错误
{{ $profile->user }}
它说无法找到该变量,所以我没有在laravel中设置关系船,因为它给出了错误或者是其他东西
错误是[属性[用户]在此集合实例上不存在。]
ProfileController.php
public function index()
{
$profile = Profile::all();
return view ('profile.show',compact('profile'));
}
正如Vahe Shak所述,您的个人资料表需要一个外键来显示user_id与users表中的id相关。 您的个人资料表迁移需要具备以下条件:
$table->integer('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
但是,编辑迁移将无法有效地进行更改。 使用新的迁移
php artisan make:migration add_foreign_to_profile
然后,迁移应如下所示:
public function up()
{
Schema::table('profiles', function(Blueprint $table)
{
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
public function down()
{
Schema::table('profiles', function(Blueprint $table)
{
$table->dropForeign('user_id');
});
}
然后,您可以运行php artisan migration
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.