Laravel Eloquent关系不起作用

时间:2016-03-12 20:56:17

标签: php laravel eloquent

我已经定义了与投资组合的用户关系,但它给我的用户模型是

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;
    protected $table = 'users';
    protected $fillable = ['name', 'email', 'password'];
    protected $hidden = ['password', 'remember_token'];

    public function portfolio()
    {
        $this->hasMany('App\Portfolio');
    }

}

我的投资组合模型

class Portfolio extends Model
{

    protected $fillable = ['user_id', 'ptitle', 'pdate','pedate','purl','languages','pdes','attachments'];

    public function user()
    {
        $this->belongsTo('App\User');
    }
    public function attachments()
    {
        $this->hasMany('App\Attachment');
    }
}

我在迁移时定义了外键我的迁移代码是

public function up()
    {
        Schema::create('portfolios', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('ptitle');
            $table->timestamps();
            $table->foreign('user_id')
                   ->references('id')
                    ->on('users')
                    ->onDelete('cascade');
        });
    }

我再次运行迁移。当我尝试获取用户投资组合时,它给我空值我在控制器use App\User;的顶部声明这个,然后我通过这个命令$user=User::find(1)找到用户,最后我这样做$user->portfolio()但是它让我无效我被困在那里2至3小时请帮帮我

2 个答案:

答案 0 :(得分:6)

你应该返回关系来获取关系数据

public function portfolio()
{
   return $this->hasMany('App\Portfolio');
}

答案 1 :(得分:0)

基本的短端示例设置(在以下示例中使用):

class User extends Model {
    public function portfolio()
    {
        //you missed the return
        return $this->hasMany('App\Portfolio');
    }

}
class Portfolio extends Model {
    public function user()
    {
        //you missed the return
        return $this->belongsTo('App\User');
    }
}

假设您有一个ID为1的用户和相关的投资组合条目:

$mUser = User::findOrFail(1); //Return User model
$mUserLazy = User::with('portfolio')->findOrFail(1); //Preload portfolio

$mPortfolioQueryBuilder = $mUser->portfolio(); //QueryBuilder

$aPortfolio = $mUser->portfolio; //Portfolio Collection
$aPortfolio = $mUserLazy->portfolio; //Portfolio Collection
$aPortfolio = $mPortfolioQueryBuilder->get(); //Portfolio Collection