Laravel错误未找到列

时间:2017-11-02 09:08:27

标签: php laravel

错误: SQLSTATE [42S22]:未找到列:1054未知列' products.id'在' where子句' (SQL:从products中选择{productsid = 1限制1)

我有桌子产品'使用&product;。'领域。不知道为什么我收到此错误。我

时出现此错误
  • 访问/产品/ {{product_id}}
  • 访问/编辑

家庭控制器:

 <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user_id = auth()->user()->id;
        $user = User::find($user_id);
        return view('home')->with('products',$user->products);
    }
}

ProductController的:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\product;

class productController extends Controller
{
        /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth',['except' => ['index','show']]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = product::orderBy('created_at','desc')->paginate(10);
        //$products = product::where('type','major')->get();
        return view('products.index')->with('products',$products);
    } 

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('products.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'title' => 'required',
        ]);
            //create product
        $product = new product;
        $product->title = $request->input('title');
        $product->venue = $request->input('venue');
        $product->city = $request->input('city');
        $product->country = $request->input('country');
        $product->description = $request->input('description');
        $product->date = $request->input('date');
        $product->user_id = auth()->user()->id;
        $product->save();

        return redirect('/products')->with('success','product Created');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $product = product::find($id);
        return view('products.show');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $product = product::find($id);
        return view('products.edit')->with('product',$product);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'title' => 'required'
        ]);

        $product = product::find($id);
        $product->title = $request->input('title');
        $product->save();

        return redirect('/products')->with('success','product updated');
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $product = product::find($id);
        $product->delete();
        return redirect('/products')->with('success','product deleted');

    }
}

Show.blade.php

@extends('layouts.app')

@section('content')

<div class="container">
    <h1 class="centre">{{$product->title}}</h1>

    <div class="well-xs">
        @if(!Auth::guest())
            @if(Auth::user()->id == $product->user_id)

                <a href="../products/{{$product->id}}/edit" class="btn btn-default">Edit</a>

                {!!Form::open(['action' => ['productcontroller@destroy', $product->product_id], 'method' => 'POST'])!!}
                    {{Form::hidden('_method', 'DELETE')}}
                    {{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
                {!!Form::close()!!}
            @endif
        @endif
    </div>

    <div>
        <div>
            <h4>product Date: {{$product->date}}</h4>

            <h4>product Venue: {{$product->venue}}</h4>

            <h4>product Location:{{$product->city}}</h4>

            <h4>product Description: </h4>
            <p>{{$product->description}} </p>
        </div>

    </div>

    <hr>
    Written on 
    </hr>

</div>
@endsection

产品表模式:我在sql中手动添加了user_id。当我尝试单独迁移到add_user_id_to_table

时,迁移不起作用
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('product_id');
        $table->string('title',200);
        $table->string('venue',200);
        $table->text('city',200);
        $table->text('country',200);
        $table->string('description');
        $table->date('date',200);
        $table->timestamps();
    });
}

user.php模型:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

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

    public function products(){
        return $this->hasMany('App\Product');
    }
}

Product.php模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    //Table NAME
    protected $table = 'products';

    //PRIMARY KEY
    public $primaryKey = 'id';

    //Timestamps
    public $timestamps =true;

    public function user(){
        return $this->belongsTo('App\User');
    }
}

2 个答案:

答案 0 :(得分:0)

更改用户模型

public function products(){
    return $this->hasMany("App\Product","product_id","product_id");
    //return $this->hasMany("App\Product","foreign_key","local_key");
}

答案 1 :(得分:0)

修改迁移时,仍需要更新数据库。所以你应该试试

php artisan migrate:fresh

这将删除您的数据库并再次迁移

此外,您无需查询控制器中的当前用户

而不是:

public function index()
{
    $user_id = auth()->user()->id;
    $user = User::find($user_id);
    return view('home')->with('products',$user->products);
}

您可以简单地使用:

public function index()
{
    return view('home')->with('products', auth()->user()->products);
}

编辑:

您的产品迁移没有定义名为id的列,而是product_id

此外,当您在该表上没有该用户的ID时,您在产品中声明了belongsTo关系。

关系belongsTo表示您拥有相关模型的ID。例如

class User extends Model
{
    public function posts()
    {
        return $this->hasMany(App\Post::class);
    }
}

class Post extends Model
{
    public function user()
    {
        return $this-belongsTo(App\User::class); 
    }
}

这是可能的,因为posts表有一个名为user_id的字段。因为帖子属于用户。

您不需要此代码:

//Table NAME
protected $table = 'products';

//PRIMARY KEY
public $primaryKey = 'id';

//Timestamps
public $timestamps =true;

Laravel自动处理所有这些,您正在定义默认值