刚刚学习laravel,跟着教程一路做,遇到了一个Relationship 莫名的问题,问题如下:
1,这是生成Articles表格的migration:
class CreateArticleTable extends Migration
{
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamp('publishat');
$table->timestamps();
$table->integer('user_id')->unsigned()->default(1);
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
2、对应的Article表的model
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $table='articles';
protected $fillable=['title','body','publishat','user_id'];
protected $dates=['publishat'];
public function setPublishatAttribute($date)
{
$this->attributes['publishat']=Carbon::createFromFormat('Y-m-d',$date);
}
public function scopePublishat($query)
{
$query->where('publishat','<=',Carbon::now()) ;
}
public function user()
{
return $this->belongsTo('App\User');
}
}
3、对应的Users表格的model文件:
<?php
namespace App;
use App\Article
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 articles()
{
return $this->hasMany('App\Article');
}
}
问题:
在tinker界面下执行:
$article = new App\Article::first();
报错:PHP Parse error: Syntax error, unexpected T_STRING, expecting T_VARIABLE or '$' on line 1
但执行 $article = new App\Article;
//没问题
然后执行:$article->first();
//正常返回数据
执行:$article->user
//返回null
同样,执行对应的 $user->articles //也返回null,
请各位帮我看看到底是哪儿出了问题,数据库都来回 migrate:refresh 好多次了,但就是解决不了问题,谢谢大家