我正试图使用laravel 5.1建立一对多关系。问题是,当我创建一个新产品时,它不属于数据库中的任何用户。我的数据库中有两个表:产品和用户。products表中的一行是user_id。
public function create()
{
return view('products.create');
}
public function store(Request $request)
{
$inputs = $request->all();
$product = Product::Create($inputs);
return redirect()->action('ProductController@index');
}
这是我的ProductController中的代码。这是我模型中的代码。
<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Product extends Model
{
protected $fillable = [
'name',
'price',
'descr',
'image',
'sale',
'user_id'
];
public $timestamps = false;
protected $table = 'products';
public function books(){
return $this->hasMany('App'Books');
}
}
不管我怎么做,我都不知道该怎么做。如果我忘记添加上面的任何内容,请告诉我。感谢
对于一对多关系或任何关系,您都需要具有正确的数据库结构。例如,在您的案例中,您有两个表products
和users
让我们只为表products
和users
创建迁移
迁移
Schema::create('users',function(Blueprint $table){
$table->increaments('id');
$table->string('name');
//and so on ...
});
因此,基本上,为了识别用户,您有users.id
列。
Schema::create('products',function(Blueprint $table){
$table->increaments('id');
$table->string('product_name');
$table->integer('user_id')->unsigned();
//and so on ...
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
现在您有了users
表和products
表。表之间的关系是用户可以拥有产品。
型号
class User extends Model {
public function products(){
return $this->hasMany(''App'Product'); //Product Model Name
}
}
现在,如果您想访问属于users
的products
,您必须在控制器中执行此操作。
$user = Users::find(1); //lets say for test we just took firs user
return $user->products()->get();
这将为您提供一个用户详细信息的干净json,以及与该特定用户关联的产品。
注意:在您的情况下,您的产品详细信息没有任何user_id关联,在这种情况下,它不会起作用,因为应该存在一些关系。
用于将数据存储到数据库
public function create()
{
return view('products.create');
}
public function store(Request $request)
{
$inputs = $request->all();
$product = Product::Create($inputs);
return redirect()->action('ProductController@index');
}
现在您正在将值大量分配到数据库中,所以$request->all()
必须具有已登录用户的user_id
因此,在products.create
视图的窗体区域中创建一个隐藏字段。
<form action="someaction" method="POST">
<input type="hidden" name="user_id" value="{{Auth::user()->id}}"/>
<input type="text" name="product_name" />
</form>
现在,您的$request->all()
方法将包含密钥user_id
及其值形式的登录用户。
CCD_ 15给出登录用户的信息;
或者,在你的控制器中,你也可以这样做。。
public function store(Request $request)
{
$request->user_id = Auth::user()->id; //assigning user_id value to the current logged in user's id (this has to be before adding the request to the inputs variable so when you execute ::Create($inputs) it will be there)
$inputs = $request->all();
$product = Product::Create($inputs);
return redirect()->action('ProductController@index');
}
希望这会有所帮助。:)