我试图查看username
和email
列,这些列是我的有效负载中的SQL db列,但是由于某些原因,它没有显示。我使用React作为前端,使用Laravel作为后端,由于某种原因,我没有看到它们。
我可能做错了什么?
这里是User.php
模型:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function posts() {
return $this->hasMany(Post::class);
}
}
这里是Posts.php
模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['body'];
public function user() {
$this->belongsTo(User::class);
}
}
这里是PostController.php
:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PostController extends Controller
{
public function create(Request $request, Post $post) {
// create post
$createdPost = $request->user()->posts()->create([
'body' => $request->body
]);
// return response
return response()->json($createdPost);
}
}
这里是web.php
:
Auth::routes();
Route::group(['middleware' => ['auth']], function () {
Route::post('/posts', 'PostController@create');
});
这是我的帖子请求:
constructor(props) {
super(props);
this.state = {
body: '',
posts: []
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleSubmit(e) {
e.preventDefault();
// this.postData();
axios.post('/posts', {
body: this.state.body
}).then(response => {
console.log(response);
this.setState({
posts: [...this.state.posts, response.data]
});
});
this.setState({
body: ''
});
}
答案 0 :(得分:1)
您错过了return
键:)。
public function user()
{
return $this->belongsTo('App\User');
^^^^^^
}
答案 1 :(得分:0)
我相信您没有正确传递外键,
protected $fillable = ['body', 'user_id'];
public function user()
{
$this->belongsTo('App\User', 'user_id');
}