提问者:小点点

我如何获得发布产品的人


我有两张桌子给卖家和产品。每个卖家都可以发布他们的产品。我已经做了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',
];}

产品模型

类别产品扩展模型{

public$table=“产品”;

受保护的$fillable=['name'、'description'、'size'、'image'、'price'、'type'];

受保护的$hidden=['password','memory_token'];

}


共2个答案

匿名用户

您可以使用雄辩来做到这一点:

您可以这样声明两个模型之间的关系:

在您的产品模型中,您可以添加:

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

匿名用户

我发现答案只是添加Auth::Guard('ps')-

    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');
     }