php - 一对多关系不起作用
问题描述
https://imgur.com/a/ob9rjIz 有两个表,一个称为 user,另一个称为 user_relation_user 我的关系是许多 user_relation_user 的用户,并且在我的迁移中。我想用 php artisan tinker 创建 10 个用户,所以我运行 factory(App\User::class, 10)->create(); 最后我访问我的数据库,所以从用户中选择 * 有 10 个用户,但在 user_relation_user 中不是 10 id 或者它是空的
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Administrator extends Model
{
protected $table = 'user_relation_user';
protected $primaryKey = 'id';
protected $fillable = ['user_id'];
public function users(){
return $this->belongsTo(User::class,'user_id');
}
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function administrator(){
return $this->hasMany(Administrator::class,'user_id');
}
}
//hasMany
我的迁移
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserRelationUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user_relation_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('user_id_admin')->unsigned();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*foreign
* @return void
*/
public function down()
{
Schema::dropIfExists('user_relation_user');
}
}
解决方案
你定义的关系是正确的,你只需要在用户模型中定义一个关系。
例子:
假设您正在开发一个博客系统,用户可以在其中发布博客。那么会有两个模型用户模型和博客模型
在用户模型中,您必须定义用户关系如下:
public function blogs()
{
return $this->hasmany(Blog::class);
}
然后在博客模型中
public function users()
{
return $this->belongsTo(User::class);
}
推荐阅读
- r - ymax 计数值
- php - 如何在 PHP 中使用 curl 进行第三方 url 重定向后获得响应
- java - 错误:没有这样的元素:无法找到元素:{"method":"link text","selector":"Order Qty"}
- teradata - where 子句如何用于 teradata 中的日期字段
- jenkins - Jenkins下的SignTool找不到与USB Token匹配的证书
- python - 如何更改句子中字符的位置?
- swift - 传递什么参数来代替 (String) -> void?
- reactjs - 如何使用酶安装找到嵌套的连接组件?
- ckan - 如何将文件上传到 CKAN 扩展包中?
- performance - Julia:有没有办法用离散集合中的条目枚举所有大小为 m × n 的矩阵?