在laravel

时间:2017-09-29 12:17:51

标签: php laravel

我这里有一个简单的问题,但我在这里遇到了ATM。

我无法理解为什么简单的Model::find($id)无效。

我有一个新的应用程序。我检查了应用程序是否成功连接到数据库。

所以我将查询更改为:

$user = DB::select("SELECT * FROM users WHERE id=".$id);

它完全有效,但如果我这样做:

$user = User::find($id);

它什么都不返回,它是空的。

我的模型看起来像这样:

class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;
    protected $dates = ['deleted_at'];

    /**
     * The table associated with the model
     * 
     * @var string
     */
    protected $table = 'users'; 

    /**
     * Indicates if the model should be timestamped
     * 
     * @var bool
     */
    public $timestamps = true;

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

    //------DEFINE RELATIONSHIPS------    
    /**

那里有什么不对?

----为问题添加了模型

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;
    protected $dates = ['deleted_at'];

    /**
     * The table associated with the model
     * 
     * @var string
     */
    protected $table = 'users'; 

    /**
     * Indicates if the model should be timestamped
     * 
     * @var bool
     */
    public $timestamps = true;

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

    //------DEFINE RELATIONSHIPS------    
    /**
     * Each User has one Picture
     * 
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function picture()
    {
        return $this->hasOne('App\Picture');
    }

    /**
     * Each User has many Ads
     * 
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function ads(){
        return $this->hasMany('App\Ad');
    }
}

这里是表格的截图。我填写了假数据:

enter image description here

3 个答案:

答案 0 :(得分:1)

使用顶部的User

use App\User;

或使用\

$user = \User::find($id);

答案 1 :(得分:0)

如果id在数据库中是整数,那么只有它才能在find中工作,否则你必须使用它 其中

$user = User::find($id);

$user = User::where('id',$id)->first();

如果你的表中没有该id的记录,那么Null会返回,但是在你的情况下它会在那里返回

答案 2 :(得分:0)

好的,我找到了解决方案。在表格描述中,我看到每次都更新deleted_at列,因此所有用户都被删除了#34;  enter image description here

我这样做是为了实现软删除功能,当我们执行迁移文件时,我们做错了:

$table->timestamp('deleted_at');

应该是

$table->dateTime('deleted_at');

我修改了那一栏:

alter table users modify deleted_at datetime;

并将当前值更新为NULL:

update users set deleted_at = null;

现在一切正常。

谢谢大家!