[英]Laravel Insert into Pivot Table
我正在尝试将数据写入数据透视表,但是得到“在null上调用成员函数guest()的成员”
这是我的代码,我哪里出问题了?
我已经尝试过了,对什么错我感到困惑
事件模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'events';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['headline', 'description', 'address', 'zip', 'longitude', 'latitude',
'position', 'country_id', 'cat_id', 'start_date', 'end_date'];
public function user()
{
return $this->belongsTo('App\User');
}
/**
* The products that belong to the shop.
*/
public function guests()
{
return $this->belongsToMany('App\Models\Guest', 'event_guest', 'guest_id', 'event_id');
}
}
访客模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Guest extends Model
{
protected $fillable = ['first_name', 'last_name', 'email'];
public function events()
{
return $this->belongsToMany('App\Models\Event', 'event_guest', 'event_id', 'guest_id');
}
}
控制者
//RSVP events
public function rsvpCheck()
{
$check = Guest::find(5);
//$guestCheck = Event::where('id',5)->first();
$check->events()->attach(2);
return $check->events;
}
尝试以这种方式进行。 将此添加到您的create_events_migration下面
Schema::create('event_guest', function (Blueprint $table) {
$table->integer('event_id')->unsigned()->index();
$table->foreign('event_id')->references('id')->on('events');
$table->integer('guest_id')->unsigned()->index();
$table->foreign('guest_id')->references('id')->on('guests');
});
在您的事件模型中使用此关系
public function guests()
{
return $this->belongsToMany(Guest::class); // include at the top: use App\Models\Guest;
}
在您的访客模型中
public function events()
{
return $this->belongsToMany(Event::class); // include at the top: use App\Models\Event;
}
在您的数据库中添加一些虚拟数据(事件和来宾之间的关系)并将此代码粘贴到您的路由中
Route::get('/testguest', function(){
$guest= Guest::first();
dd($company->events);
});
反之亦然
路线:: get('/ testevents',function(){
$event= Event::first();
dd($event->guests);
});
让我知道您到目前为止是否可以正常使用并获得了虚拟数据
按照@Mike的建议更改您的关系方法。
如下更改事件模型中的guests()
方法:
public function guests()
{
return $this->belongsToMany('App\Models\Guest');
}
如下更改客户模型中的events()
方法:
public function events()
{
return $this->belongsToMany('App\Models\Event');
}
现在,要将数据插入数据透视表,您有两种情况:
1)没有数据
public function rsvpCheck()
{
$check = Guest::findOrFail(5);
$check->events()->attach(2);
return $check->events();
}
2)需要在数据透视表中插入额外的数据
public function rsvpCheck()
{
$data = ['attribute'=>'value'];//replace this with the data you want to insert
$check = Guest::findOrFail(5);
$check->events()->attach(2,$data);
return $check->events();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.