大家好我已经用映射制作了几个类:
class Like extends Model
/**
* Returns like's author
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function owner(){
return $this->belongsTo('App\User');
}
/**
* Returns tweet
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function tweet(){
return $this->belongsTo('App\Tweet');
}
Class Tweet extends Model
/**
* Returns tweet's author
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function owner(){
return $this->belongsTo('App\User');
}
/**
* Returns tweet's likes
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function likes(){
return $this->hasMany('App\Like');
}
Class User extends Authenticatable
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'email', 'password', 'www', 'first_name', 'last_name', 'status'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
];
/**
* Returns user's tweets
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function tweets(){
return $this->hasMany('App\Tweet');
}
/**
* Returns user's likes
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function likes(){
return $this->hasMany('App\Like');
}
现在的问题是我的两个maping无法正常工作。在Like model' owner'方法返回null,虽然它应该返回一条记录,' tweet'另一只手的方法按预期工作。
在Tweet模型中,'所有者'方法也返回null。所有其他方法都按预期工作。我无法找到我犯错误的地方,也无法理解为什么来自Like模型的推文方法正在工作且所有者不是......
也许迁移找到可能有帮助
public function up()
{
Schema::create('likes', function (Blueprint $table) {
$table->increments('id');
$table->integer('tweet_id');
$table->integer('user_id');
$table->string('status');
$table->timestamps();
});
}
public function up()
{
Schema::create('tweets', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('content');
$table->string('score');
$table->string('views');
$table->string('status');
$table->timestamps();
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email')->unique();
$table->string('password',60);
$table->string('www');
$table->string('first_name');
$table->string('last_name');
$table->string('status');
$table->timestamps();
});
答案 0 :(得分:0)
您必须指定外键:
Schema::table('tweets', function ($table) {
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
答案 1 :(得分:0)
你的推文& 赞模型将owner()
作为belongsTo()
关系方法。哪个没问题,但您必须将外键指定为第二个参数:
/**
* Returns like's author
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function owner()
{
return $this->belongsTo('App\User', 'user_id');
}
Laravel docs:
Eloquent通过检查关系方法的 名称 并使用
_id
为方法名称添加后缀来确定默认外键名称。