所以我試圖建立一個用戶可以有許多訂單和一個訂單有2個用戶(例如:客戶和員工服務該訂單)的結構。Laravel 5.1如何將訂單附加到使用數據透視表的用戶?
這是我的遷移:
訂單給用戶:
Schema::create('order_user', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('order_id')->unsigned()->index();
$table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
$table->timestamps();
});
訂單:
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
$table->string('boostFrom')->nullable();
$table->string('boostTo')->nullable();
$table->string('numGames')->nullable();
$table->decimal('totalPrice');
$table->string('ipnStatus');
$table->timestamps();
});
用戶:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
我沒有設置的關係還沒有,因爲我與他們一起測試在我的用戶和訂單模型中。但是,當我嘗試使用的順序連接到用戶:
$user->order()->attach(4);
我得到有關Builder.php說附上()不存在錯誤,但我是繼laravel 5.1文檔,試圖連接順序。
請你讓我知道我應該如何構造一切,所以當創建訂單時,我可以將其附加到用戶。
感謝
的要求:
class Order extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'orders';
public function users()
{
return $this->hasMany('App\Models\User');
}
}
class User extends Model implements AuthenticatableContract, CanResetPasswordContract, HasRoleAndPermissionContract
{
use Authenticatable, CanResetPassword, HasRoleAndPermission;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
protected $guarded = ['id'];
public function orders()
{
return $this->hasMany('App\Models\Order');
}
}
錯誤修補匠:
>>> $user->orders()->attach(4)
BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::attach()'
能不能請你從你的'User'和'Order'車型後的代碼。 – Bogdan
我剛剛添加了,現在 – Elevant
Infact我嘗試了一些使用修補程序的東西,但我還沒有能夠添加任何東西到我的Order_User表。 – Elevant