在laravel-8中将PROJECTS表中的PRODUCT表中的ID调用为forignId name product_id [英] Call id from product table in projects table as forignId name product_id in laravel-8

查看:23
本文介绍了在laravel-8中将PROJECTS表中的PRODUCT表中的ID调用为forignId name product_id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个名为usersproductsprojects的表。 产品和项目有太多的关系 产品具有id此id属于多个项目 这是我的Products.php表

Schema::create('products', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->text('detail');
    $table->string('color');
    $table->string('image');
    $table->string('logo');
    $table->unsignedBigInteger('user_id');
    $table->timestamps();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

这是projects.php thable

Schema::create('projects', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('chapter_name', 255)->nullable();
    $table->string('sub_section_name', 500)->nullable();
    $table->string('title_1', 255)->nullable();
    $table->string('description_1', 5000)->nullable();
    $table->string('image_1', 255)->nullable();
    $table->string('image_2', 255)->nullable();
    $table->string('image_3', 255)->nullable();
    $table->string('title_2', 255)->nullable();
    $table->string('description_2', 5000)->nullable();
    $table->string('title_3', 255)->nullable();
    $table->string('description_3', 255)->nullable();
    $table->string('video_1', 255)->nullable();
    $table->string('video_2', 255)->nullable();
    $table->string('video_3', 255)->nullable();
    $table->unsignedBigInteger ('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    // $table->foreignId('product_id')->nullable();
    $table->unsignedBigInteger('product_id')->references('id')->on('products')->onDelete('cascade');
    $table->timestamp('created_at')->useCurrent();
    $table->timestamp('updated_at')->nullable();
});
在我的ProjectImport.php中,我希望调用product_id=id of products表 这是我的项目导入.php

public function model(array $row)
{
    return new Project([
        'chapter_name'     => $row['chapter_name'],
        'sub_section_name' => $row['sub_section_name'],
        'title_1'          => $row['title_1'],
        'description_1'    => $row['description_1'],
        'image_1'          => $row['image_1'],
        'image_2'          => $row['image_2'],
        'image_3'          => $row['image_3'],
        'title_2'          => $row['title_2'],
        'description_2'    => $row['description_2'],
        'title_3'          => $row['title_3'],
        'description_3'    => $row['description_3'],
        'video_1'          => $row['video_1'],
        'video_2'          => $row['video_2'],
        'video_3'          => $row['video_3'],
        'user_id'          => auth()->user()->id,
        'product_id'       => Product::where('user_id',Auth::id())->pluck('id') // Here i want product_id = product table id
        // 'product_id' => id()->id
    ]);
}

关系是一对多和一对多。在这里,用户有许多产品的id和每个产品可以有许多项目。 这是ProductController.php

<?php

namespace AppHttpControllers;

use AppModelsProduct;
use IlluminateHttpRequest;
use AppModelsUser;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesHash;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */

    //  public function indexGetProducts(){
    //      return User::find(auth()->user()->id)->getProducts;
    //  }

    public function index()
    {
        //  $products = Product::latest()->paginate(20);
        $products = Product::where('user_id',auth()->user()->id)->latest()->paginate(20);

         return view('products.index',compact('products'))
         ->with('i', (request()->input('page', 1) - 1) * 5);
        // $products= Product::where('user_id',auth()->user()->id)->orderby('created_at','desc')->get();

        // return view('products.index',compact('products'))->with('i', (request()->input('page', 5) - 1) * 5);

    }

    function authapi(Request $request)
    {
        $user = User:: where('email', $request->email)->first();
        if(!$user || !Hash::check($request->password, $user->password)){
            return response([
                'message' => ['These credentials do not match our records.']
            ],404);
        }

        $token = $user -> createToken('my-app-token')->plainTextToken;

        $response = [
            'user' => $user,
            'token' => $token
        ];

        return response($response,201);
    }

    function all_app_jsons(){
        // return Product::all();
        return User::find(auth()->user()->id)->getProducts;
    }

    function search_by_name($name){
        return Product::where('name','like','%'.$name.'%')->get();
    }

    function search_by_id($id){
        return Product::where('id',$id)->
        where('user_id',auth()->user()->id)->get();
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return IlluminateHttpResponse
     */
    public function create()
    {
        return view('products.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        //$tag = Product::create($request->all());

        //return redirect()->route('admin.tags.index');
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
            'color' => 'required',
            'image' => 'required|image|mimes:png,jpg,jpeg|dimensions:width=1080,height=1920|max:2048',
            'logo' => 'required|image|mimes:png,jpg,jpeg|dimensions:width=512,height=512|max:1024',
        ]);

          $input = $request->all();
         // $request->validated();
        $input['user_id'] = auth()->user()->id;

        if ($image = $request->file('image')) {
            $destinationPath = 'image/';
            $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $profileImage);
            $input['image'] = "$profileImage";
        }

        if ($logo = $request->file('logo')) {
            $destinationPath = 'logo/';
            $profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
            $logo->move($destinationPath, $profileLogo);
            $input['logo'] = "$profileLogo";
        }

        Product::create($input);

        return redirect()->route('projects.index')
                        ->with('success','Product created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  AppProduct  $product
     * @return IlluminateHttpResponse
     */
    public function show(Product $product)
    {
        return view('products.show',compact('product'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  AppProduct  $product
     * @return IlluminateHttpResponse
     */
    public function edit(Product $product)
    {
        return view('products.edit',compact('product'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  AppProduct  $product
     * @return IlluminateHttpResponse
     */
    // public function update(Request $request, Product $product)
    public function update(Request $request, $product_id)
    {
        $user_id =  Auth::user()->id ;

        $request->validate([
            'name' => 'required',
            'detail' => 'required',
            'color' => 'required',
        ]);

        $input = $request->all();

        if ($image = $request->file('image')) {
            $destinationPath = 'image/';
            $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $profileImage);
            $input['image'] = "$profileImage";
        }else{
            unset($input['image']);
        }

        if ($logo = $request->file('logo')) {
            $destinationPath = 'logo/';
            $profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
            $logo->move($destinationPath, $profileLogo);
            $input['logo'] = "$profileLogo";
        }else{
            unset($input['logo']);
        }

        $product_id->update($input);

        return redirect()->route('products.index')
                        ->with('success','Product updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  AppProduct  $product
     * @return IlluminateHttpResponse
     */
    public function destroy(Product $product)
    {
        $product->delete();

        return redirect()->route('products.index')
                        ->with('success','Product deleted successfully');
    }

    // function indextwo(){
    //     //return DB::select("select * from  products");
    //    //DB::table('products')->orderBy('id','desc')->first();
    //    return Product::orderBy('id', 'DESC')->first();
    // }

}

这是ProjectController.php

<?php

namespace AppHttpControllers;

use AppExportsUsersExport;
use AppModelsProject;
use AppImportsProjectsImport;
use AppModelsProduct;
use MaatwebsiteExcelFacadesExcel;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;

class ProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        // $projects = Project::where('user_id',auth()->user()->id)->latest()->paginate(20);
        // $projects = Project::where('user_id',auth()->user()->id)->where('product_id')->latest()->paginate(20);
        // $projects = Project::where('user_id',auth()->user()->id)->latest('product_id',8) ->paginate(20);
        // $projects = Project::whereIn('product_id',Product::where('user_id',Auth::id())->pluck('id')->toArray())->latest();
        // $projects = Project::whereIn('product_id',Product::where('user_id',Auth::id())->pluck('id')->toArray())->latest()->paginate(20);

        $projects = Project::whereIn('product_id',Product::where('user_id',Auth::id())->pluck('id')->toArray())->latest()->paginate(20);


        return view('projects.index', compact('projects'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return IlluminateHttpResponse
     */
    public function create()
    {
        return view('projects.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        $request->validate([
            'chapter_name' => 'required',
            'sub_section_name' => 'required',
            'title_1' => 'required',
            'description_1' => 'required',
            'image_1' => 'required',
            'image_2' => 'required',
            'image_3' => 'required',
            'title_2' => 'required',
            'description_2' => 'required',
            'title_3' => 'required',
            'description_3' => 'required',
            'video_1' => 'required',
            'video_2' => 'required',
            'video_3' => 'required',
        ]);

        // $input = $request->all();
        // $input['user_id'] = auth()->user()->id;
        // $input['product_id'] = $id;
        $input = Project::whereIn('product_id',Product::where('user_id',Auth::id())->pluck('id'));


        Project::create($input);

        return redirect()->route('project.index')
                        ->with('success','Product created successfully.');

    }

    /**
     * Display the specified resource.
     *
     * @param  AppModelsProject  $project
     * @return IlluminateHttpResponse
     */
    public function show(Project $project)
    {
        // $category = $project->category;
        return view('projects.show', compact('project'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  AppModelsProject  $project
     * @return IlluminateHttpResponse
     */
    public function edit(Project $project)
    {
        return view('projects.edit', compact('project'));
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  AppModelsProject  $project
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, Project $project)
    {
        // $user_id =  Auth::user()->id ;

        $request->validate([
            'chapter_name' => 'required',
            'sub_section_name' => 'required',
            'title_1' => 'required',
            'description_1' => 'required',
            'image_1' => 'required',
            'image_2' => 'required',
            'image_3' => 'required',
            'title_2' => 'required',
            'description_2' => 'required',
            'title_3' => 'required',
            'description_3' => 'required',
            'video_1' => 'required',
            'video_2' => 'required',
            'video_3' => 'required',
        ]);

        $input = $request->all();

        $project->update($input);

        return redirect()->route('project.index')
                        ->with('success','Product updated successfully');
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  AppModelsProject  $project
     * @return IlluminateHttpResponse
     */
    public function destroy(Project $project)
    {
        $project->delete();

        return redirect()->route('projects.index')
            ->with('success', 'Project deleted successfully');
    }

    public function importProject()
    {
        Excel::import(new ProjectsImport, request()->file('file'));

        return back()->with('success','Project created successfully.');
    }

    public function export()
    {
        return Excel::download(new UsersExport, 'projects.xlsx');
    }
}

这是用户模型user.php

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function Products(){
        return $this->hasMany('AppModelsProduct');

    }

    public function Project(){
        return $this->hasMany('AppModelsProject');
    }
    // public function products(){
    //     return $this->hasMany(Product::class);
    // }

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}

这是产品型号Product.php

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'detail', 'image','color','logo','user_id'
    ];

    public function User(){
        return $this->belongsTo(User::class);
    }

    public function Project(){
        return $this->hasMany('AppModelsProject');
    }
}

这是项目模型project.php

class Project extends Model
{
    use HasFactory;

    protected $fillable = [
        'chapter_name',
        'sub_section_name',
        'title_1',
        'description_1',
        'image_1',
        'image_2',
        'image_3',
        'title_2',
        'description_2',
        'title_3',
        'description_3',
        'video_1',
        'video_2',
        'video_3',
        'user_id',
        'product_id'
    ];

    public function User(){
        return $this->belongsTo(User::class);
    }

    public function Product(){
        return $this->belongsTo(Product::class);
    }
}

产品

由项目::Where(‘推荐答案_id’,Product::Where(‘User_id’,Auth::id())->;pluck(‘id’)->;last())->;delete();)解决 在项目中导入

这篇关于在laravel-8中将PROJECTS表中的PRODUCT表中的ID调用为forignId name product_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆