我有两张卖家和产品表。每个卖家都可以发布他们的产品我已经完成了post方法。
我如何知道每个产品的销售商,以及如何展示它?
class ProductController extends Controller
{
public function index()
{
return view('ps.products.create');
}
public function store(Request $request)
{
$product = new Product;
$product->name = $request->name;
$product->description = $request->description;
$product->type = $request->type;
$product->size = $request->size;
$product->price = $request->price;
$product->image = $request->image;
$product->save();
return view('pshome');
}
public function show()
{
$id = DB::table('product')->get();
return view('viewproduct', ['id' => $id]);
}
}
卖家模型
class Ps extends Authenticatable{ use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name','lastname','email', 'password', 'username','phone',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];}
产品型号
类Product扩展Model {
public $ table =" Product";
受保护的$ fillable = ['名称','说明','尺寸','图片','价格&# 39;,'类型'];
受保护$ hidden = ['密码',' remember_token'];
}
答案 0 :(得分:0)
你可以使用Eloquent来做到这一点:
你可以像这样声明两个模型之间的关系:
在您的产品型号中,您可以添加:
public function ps()
{
return $this->belongsTo('App\Ps');
}
你可以在ps模型中添加:
public function products()
{
return $this->hasMany('App\Products');
}
所以,你的商店方法可能如下所示:
use Auth;
public function store(Request $request)
{
$ps = Auth::ps()
$product = new Product;
$product->name = $request->name;
$product->description = $request->description;
$product->type = $request->type;
$product->size = $request->size;
$product->price = $request->price;
$product->image = $request->image;
$ps->products()->save($product);//this save the product and the relarion to the user
return view('pshome');
}
然后你可以知道每件产品: 在你的控制器中放了这样的东西:
public function something()
{
$ps = Ps::with("products")->all()
return view('viewproduct', compact("ps"));
}
并在你的刀片中:
@foreach ($ps as $ps)
$ps->products->id
@endforeach
您可以在此处详细了解关系:
https://laravel.com/docs/5.4/eloquent-relationships
答案 1 :(得分:0)
I found the answer just add "Auth::guard('ps')->-id to get who posted the product.
public function store(Request $request){
$product = new Product;
$product->image = $request->image;
$product->name = $request->name;
$product->description = $request->description;
$product->type = $request->type;
$product->ps_id = **Auth::guard('ps')->user()->id;**
$product->ps_name = **Auth::guard('ps')->user()->name;**
$product->size = $request->size;
$product->price = $request->price;
$product->save();
return view('pshome');
}