我已經有一些問題,使我登錄的用戶和他想參加工作的事件之間發生關係。 我真的採取了很多步驟來做類似於我對角色用戶所做的事情。但在這裏我有一些問題,因爲我的用戶使用模型用戶,事件使用模型HomeModel和其他3個模型來建立關係和連接到表SaveEvent。 有我的代碼。我希望有人能告訴我如何計算出來,因爲我浪費了2天,解決我的問題:Laravel 5.4的關係不工作不能附加第二個參數
型號HomeModel
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class HomeModel extends Model
{
protected $table = 'events'; // you may change this to your name table
\t public $timestamps = true; // set true if you are using created_at and updated_at
\t protected $primaryKey = 'id'; // the default is id
/**
* Is it an all day event?
*
* @return bool
*/
public function isAllDay()
{
return (bool)$this->day;
}
}
型號用戶
<?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 = [
'lastname', 'name', 'phonenumber', 'email', 'password', 'user_id' ,
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roles()
{
return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
}
public function hasAnyRole($roles)
{
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role)) {
return true;
}
}
} else {
if ($this->hasRole($roles)) {
return true;
}
}
return false;
}
public function hasRole($role)
{
if ($this->roles()->where('name', $role)->first()) {
return true;
}
return false;
}
public function events()
{
return $this->belongsToMany('App\SaveEvent')->withTimestamps();
}
}
模型SaveEvent
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SaveEvent extends Model
{
\t
public function users()
{
return $this->belongsToMany('App\User');
}
}
表到關係
+------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| users_id | int(10) unsigned | NO | MUL | NULL | |
| events_id | int(10) unsigned | NO | MUL | NULL | |
+------------+------------------+------+-----+---------+----------------+
public function acceptEvent($id)
{
$events_id = HomeModel::find($id);
$users_id = new SaveEvent;
$users_id->users_id=Auth::id();
$users_id->save();
$users_id->events()->attach($events_id);
return redirect()->back();
}
存在SaveEvent沒有事件關係,這可不行:$ users_id-> events()因爲$ users_id是一個SaveEvent的實例 – Indra
好吧,所以我應該d這與家模,但家模使用表的事件,我不知道如何附加這個 – Mariusz
是'HomeModel'事件?你的班級似乎是這樣說的,但這沒有意義。使用明智的名字,以便人們可以理解你在做什麼。無論如何https://laravel.com/docs/5。4 /口才,關係#多態,關係可能會有所幫助 – apokryfos