【问题标题】:Laravel error Column not foundLaravel 错误列未找到
【发布时间】:2018-04-14 17:51:02
【问题描述】:

错误: SQLSTATE [42S22]:未找到列:1054 'where 子句'中的未知列 'products.id'(SQL:select * from products where products.id = 1 限制 1)

我确实有带有“product.id”字段的表“产品”。不知道为什么我会收到这个错误。我收到此错误时我

  • 访问/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);
    }
}

产品控制器:

<?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

Products 表架构:我在 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');
    }
}

【问题讨论】:

  • 你的数据库表架构是什么?
  • 错误发生在哪一行?你能展示你的模型类吗?
  • 错误提示您的products 表中没有user_id
  • 错误提示 products.user_id 不存在,并且您共享了您的 events 表架构!
  • 在您的产品表中,您有public $primaryKey = 'id';,但您的迁移使用product_id 作为键。您应该使用id 作为主要的自动递增键。这就是约定。

标签: php laravel


【解决方案1】:

改变你的用户模型

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

【讨论】:

  • 谢谢 :) 我稍微更新了这个问题。可能会有所作为。很抱歉造成混乱
  • @joem : 更改您的用户模型关系键
【解决方案2】:

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

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

此外,您在产品与用户之间声明 belongsTo 关系,而您没有该表上的用户 ID。

关系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 会自动处理所有这些,您正在定义默认值

【讨论】:

  • 谢谢 :) 我稍微更新了这个问题。可能会有所作为。很抱歉造成混乱
  • 啊仍然无法让它工作:顺便说一句,我正在关注本教程系列:youtube.com/watch?v=42l4nHl_aUM
猜你喜欢
  • 2016-11-06
  • 1970-01-01
  • 1970-01-01
  • 2014-08-29
  • 2018-08-03
  • 2015-02-04
  • 2018-01-04
  • 2016-08-05
  • 2014-10-02
相关资源
最近更新 更多