我在http://localhost:8000/messages
为用户获取空值。我试图在Message模型中获取用户表值。它还在控制台中提供空值。
路线
Route::get('/messages', function () {
return App\Message::with('user')-> get();
})-> middleware('auth');
模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
protected $fillable = ['message'];
public function user()
{
return $this->belongsTo(User::class);
}
}
用户型号代码:
<?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 messages()
{
return $this-> hasMany(Message::class);
}
}
快照
答案 0 :(得分:0)
messages
表必须user_id
具有正确的用户ID才能使belongsTo
关系有效。
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many-inverse