hasMany或hasManyThrough通过N个模型的链

时间:2015-02-17 08:27:44

标签: php laravel laravel-4 orm eloquent

如何让所有提交的内容属于特定用户? 试试这个:

$user=User::find(1);        
dd($user->submissions);

投掷错误:

Call to undefined method Illuminate\Database\Query\Builder::hasMany()

我是否必须遍历模型?

以下是模型:

class User extends Eloquent implements ConfideUserInterface, BillableInterface
{
    public function categories()
    {
        return $this->hasMany('Category');
    }
    public function forms()
    {
        return $this->hasManyThrough('App\Models\Form', 'Category');
    }

    public function submissions()
    {
        return $this->hasMany('Category')->hasMany('Form')->hasMany('Submission');
    }
}

class Category extends \Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
    public function forms()
    {
        return $this->hasMany('App\Models\Form');
    }
    public function submissions()
    {
        return $this->hasManyThrough('Submission', 'App\Models\Form', 'id', 'form_id');
    }
}

namespace App\Models;

class Form extends \Eloquent {
    public function user()
    {
        return $this->category->user();
    }
    public function category()
    {
        return $this->belongsTo('Category');
    }
    public function submissions()
    {
        return $this->hasMany('Submission');
    }
}

class Submission extends \Eloquent {
    public function user()
    {
        return $this->form->category->user();
    }
    public function category()
    {
        return $this->form->category();
    }
    public function form()
    {
        return $this->belongsTo('App\Models\Form');
    }
}

2 个答案:

答案 0 :(得分:1)

对于链接关系而言,这并没有真正发挥作用......

你能做什么,是这样的:

$submissions = Submission::whereHas('form.category.user', function($q){
    $q->where('id', 1);
})->get();

注意具有嵌套关系的whereHas仅在最新的Laravel 4版本中添加。请务必composer update

答案 1 :(得分:0)

如果我没有错误地提出你的问题,你需要正确定义关系。

根据laravel 4.2,您可以使用以下类型的代码来定义关系:

class User extends \Eloquent implements ConfideUserInterface, BillableInterface{
    //...

    public function submissions(){
        return $this->hasMany('Submission');
    }
}

//...

class Submission extends \Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
    //...
}

要进一步阅读,请查看:http://laravel.com/docs/4.2/eloquent#relationships