插入数据透视表


Laravel Insert into Pivot Table

我试图将数据写入数据透视表,但我得到"在null上调用成员函数guests() "

这是我的代码,我哪里出错了?

我已经试过了,我很困惑什么是错的

事件模型

    <?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');
    }
}
<<p> 客人模型/strong>
     <?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;
}

按照@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();
}

试着这样做。将此添加到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');
    });

Event模型中使用这个关系

public function guests()
    {
        return $this->belongsToMany(Guest::class); // include at the top:  use App'Models'Guest;
    }

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,函数(){

            $event= Event::first();
            dd($event->guests);
        });

让我知道你是否能工作到目前为止,并得到你的虚拟数据