【发布时间】:2017-03-15 17:26:06
【问题描述】:
我正在控制器中创建功能,我想在其中附加用户和他的订单。首先,我在 User 和 Orders 两个模型之间建立关系。
这是User模型中的函数:
public function orders(){
return $this->belongsToMany('App\Orders', 'user_orders', 'user_id', 'order_id');
}
这是Orders 模型中的函数:
public function users(){
return $this->belongsToMany('App\User', 'user_orders', 'order_id', 'user_id');
}
这是新表user_orders,我想在其中附加具有我提到的这种关系的用户订单:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserOrdersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user_orders', function (Blueprint $table) {
$table->increments('id');
/*$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('order_id')->unsigned();
$table->foreign('order_id')->references('id')->on('orders');*/
$table->integer('user_id');
$table->integer('order_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('user_orders');
}
}
最后,这是我获取带有请求和订单 ID 的用户名并尝试将订单附加到给定用户的函数。
public function makeOrder(Request $request, $id){
$user = User::where('name', $request['username'])->first();
$findorder = Orders::find($id);
$user->orders()->detach();
$user->orders()->attach(Orders::where('id', $findorder))->first();
return redirect()->back();
}
我还检查了我是否获得了正确的用户名和订单 ID,并且代码的前两行运行良好,但是当我尝试附加订单时出现此错误:
ErrorException in Str.php line 289:
Object of class Illuminate\Database\Query\Builder could not be converted to string
有什么想法吗?
【问题讨论】: