bluesnow

155 经验值

多谢回复 ,php 版本为7.0,

执行:>>> $article = App\Article::first();

=> App\Article {#715
     id: 1,
     title: "CPU宸环",
     body: "php artisan migrate:refresh",
     publishat: "2016-11-24 18:33:53",
     created_at: "2016-11-24 18:33:53",
     updated_at: "2016-11-24 18:33:53",
     user_id: 1,
   }

在教主回答了这个问题后,居然这个问题就直接自动解决了,除了多那个NEW之外,会是laravel的缓存在作怪吗??再次感谢博主!

刚刚学习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 好多次了,但就是解决不了问题,谢谢大家

@746019546 博主前段时间忙重修学分的事去了,耽误了近2个月基本上没有更新,所以你没有赶上这个优惠也没有什么损失,想要学习就买

博主前段时间忙重修学分的事去了,耽误了近2个月基本上没有更新,所以你没有赶上这个优惠也没有什么损失,想要学习就买吧

刚订阅没几天就出个 “现在订阅,多赠送两个月时间 !” 这这这


博主,偶是不是也有份啊?啊啊啊  。。。