我正在尝试使用Laravel和Vue.js创建一个聊天框。我在网上关注tutorial。几乎每一步都跟着发球,我不知道为什么我没有得到理想的结果。这是我到目前为止所做的:
我创建了一个User模型和一个带有正确表格列和迁移的Message模型。在User模型中,我与Message模型建立了hasMany关系。在Message模型中,我与User建立了belongsTo关系。
当我进入修补时,我可以这样做:
factory(App\User::class)->create()
很好,就像教程中的人可以做的那样。但是当我尝试做的时候:
App\User::find(4)->messages()->created(['message'=> "Hello from Sharon"])
我收到此错误:
BadMethodCallException with message 'Method Illuminate\Database\Query\Builder::messages does not exist.'
这是我的代码:
用户模型:
<?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','api_token',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function messages()
{
return $this->hasMany(Message::class);
}
}
消息模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
protected $fillable = ['message'];
public function user()
{
return $this->belongsTo(User::class);
}
}
邮件迁移:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->text('message');
$table->integer('user_id')->unsigned();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('messages');
}
}
如果你能让我知道我做错了什么,我真的很感激。谢谢。
答案 0 :(得分:1)
重新启动php artisan修补程序并重新运行代码。它有效:)
答案 1 :(得分:0)
似乎你收到了这个错误:
BadMethodCallException with message 'Method Illuminate\Database\Query\Builder::created does not exist.'
要将模型保存到关系,请使用create
方法,但不能使用created
方法,例如:
App\User::find(4)->messages()->create(['message'=>'Hello from Sharon']);
答案 2 :(得分:0)
而不是App\User::find(4)->messages()->created(['message'=> "Hello from Sharon"])
尝试使用
App\User::find(4)->messages()->create(['message'=> "Hello from Sharon"])
或
App\User::find(4)->messages()->save(['message'=> "Hello from Sharon"])