【问题标题】:Insert into many to many relation table in Laravel在 Laravel 中插入多对多关系表
【发布时间】:2019-01-14 11:46:54
【问题描述】:

在我的 laravel 项目中,我有一些表格,我想在其中 2 个表格之间插入多对多关系。我想将一个用户(必须是一种更清洁的类型)绑定到当前经过身份验证的主机用户的许多房子中。为此,我在 Controller 中实现了以下功能:

public function hireCleanerToHouse (Request $request)
{
  $house_id = $request->houseAssign;
  $email = $request->email;
  $house = House::find($house_id);
  $cleanerUser = User::where('email', $email)->first();
  if ($cleanerUser && $house){
    $cleanerUser->houses()->attach($house);
  }

  return response()->json('success', 200);
}

我可能错过了不能让我插入任何数据的逻辑细节。我是使用 laravel 和 Eloquent ORM 的新手。

为了帮助更好地理解,这里是来自项目的模型。处理分隔表 (CRUD) 的功能都可以正常工作。

如果有其他提示可以提高可读性,或者我忽略了一些最佳实践,我会很乐意接受。

用户:

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 host()
{
    return $this->hasOne(Host::class);
}

public function cleaner()
{
    return $this->hasOne(Cleaner::class);
}

}

房子:

class House extends Model
{
protected $fillable = ['name', 'address', 'host_id'];

protected $dates = ['created_at', 'updated_at'];

protected $appends = ['next_cleaning'];

public function host()
{
    return $this->belongsTo(Host::class);
}

public function cleaners()
{
    return $this->belongsToMany(
        Cleaner::class,
        'cleaners_houses',
        'house_id',
        'cleaner_id'
    );
}

public function cleanings()
{
    return $this->hasMany(CleaningProject::class);
}

public function getNextCleaningAttribute()
{
    return $this->cleanings()->orderBy('created_at', 'desc')->first();
}
}

清洁工:

class Cleaner extends Model
{
protected $dates = ['created_at', 'updated_at'];

public function houses()
{
    return $this->belongsToMany(
        House::class,
        'cleaners_houses',
        'cleaner_id',
        'house_id'
    );
}

public function hosts()
{
    return $this->belongsToMany(
        Host::class,
        'cleaners_hosts',
        'cleaner_id',
        'host_id'
    );
}

public function user()
{
    return $this->belongsTo(User::class);
}

public function cleanings()
{
    return $this->hasMany(CleaningProject::class);
}

public function getNameAttribute()
{
    return $this->user->name;
}

}

主持人

class Host extends Model
{
protected $dates = ['created_at', 'updated_at'];

protected $appends = ['name'];

public function houses()
{
    return $this->hasMany(House::class);
}

public function cleaners()
{
    return $this->belongsToMany(
        Cleaner::class,
        'cleaners_hosts',
        'host_id',
        'cleaner_id'
    );
}

public function user()
{
    return $this->belongsTo(User::class);
}

public function getNameAttribute()
{
    return $this->user->name;
}
}

而且已经创建了将许多 Cleaners 绑定到许多 House 的迁移:

迁移

class CreateCleanersHousesTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('cleaners_houses', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('cleaner_id')->references('id')->on('cleaners');
        $table->integer('house_id')->references('id')->on('houses');
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('cleaners_houses');
}

}

【问题讨论】:

  • 我能否建议您清理一下您提供的代码,以便更快、更轻松地了解您的要求。

标签: php mysql laravel eloquent


【解决方案1】:

这是我找到的解决方案:

public function hireCleanerToHouse (Request $request)
{
  $email = $request->email;
  $houseId = $request->idHouse;
  $idUserEmail = User::where('email', $email)->first();
  $cleaner = Cleaner::where('user_id', $idUserEmail->id)->first();
  $house = House::find($houseId);
  $cleaner->houses()->attach($house->id);
  return response()->json([$cleaner, $house], 200);
}

如您所见,问题是因为模型 Cleaner 仅包含“id”和“user_id”,所以我必须首先获取 user.id 并找到 user_id = user.id 的清洁器。

我也没有在 attach() 中传递 $house->id 来匹配关系。它现在工作正常。希望它可以帮助别人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 2020-07-06
    • 2011-12-23
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多