如何获取发布产品的人
Posted
技术标签:
【中文标题】如何获取发布产品的人【英文标题】:How do I obtain who posted a product 【发布时间】:2018-02-05 21:32:07 【问题描述】:我有两张表用于卖家和产品。每个卖家都可以发布他们的产品。 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',
];
产品型号
类产品扩展模型
公共 $table = "产品";
protected $fillable = ['name','description','size','image','price','type'];
protected $hidden = ['password', 'remember_token'];
【问题讨论】:
在产品表中存储auth()->id()
?
您能向我们展示您的产品和卖家型号吗?
嗨莱昂纳多,我已经编辑了问题
你的卖家和产品有一对一的关系吗?
【参考方案1】:
你可以使用 Eloquent 来做到这一点:
你可以像这样声明两个模型之间的关系:
在您的产品模型中,您可以添加:
public function ps()
return $this->belongsTo('App\Ps');
在您的 ps 模型中,您可以添加:
public function products()
return $this->hasMany('App\Products');
所以,您的 store 方法可能如下所示:
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/1) BadMethodCallException 方法 ps 不存在。这是什么意思? 将代码更新为您现在拥有的代码,并显示引发该错误的代码部分。 哦,我明白了,生产控制器中的第 39 行有什么 $ps = Auth::Ps()//P大写【参考方案2】:我找到了答案,只需添加Auth::guard('ps')->id
即可了解发布产品的人。
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');
【讨论】:
以上是关于如何获取发布产品的人的主要内容,如果未能解决你的问题,请参考以下文章