我这里有一个简单的问题,但我在这里遇到了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');
}
}
这里是表格的截图。我填写了假数据:
答案 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)