【问题标题】:Laravel relationships not by ID'sLaravel 关系不是 ID 的
【发布时间】:2014-12-09 15:56:31
【问题描述】:

我有几个这样的表:

作者表 - ID - book_id - 名称

图书桌 - ID - 参考 - 作者 - 标题

books 表上的 ref 与 authors 表上的 book_id 相同,但在我看来,我似乎无法通过这样做来获取作者的书:

{{ $author->books->first()->title }}

我的作者和书籍模型如下所示:

class Authors extends \Eloquent {

protected $guarded = ['id'];

public $table = 'authors';

public $timestamps = false;

public function books()
{
    return $this->hasMany('Books', "author","name");
}

 }


 class Books extends \Eloquent {

protected $guarded = ['id'];

public $timestamps = false;

public function author()
{
    return $this->hasOne('Authors');
}

public function categories(){
    return $this->hasMany('Categories');
}

}

真的需要一些帮助。

【问题讨论】:

    标签: php laravel-4 eloquent


    【解决方案1】:

    您可以在hasMany 中传递外键和本地键,但看起来您将author 作为外键传递,name 作为本地键传递。外键应该是ref,本地键应该是book_id

    class Authors extends \Eloquent {
    
        protected $guarded = ['id'];
    
        public $table = 'authors';
    
        public $timestamps = false;
    
        public function books()
        {
            return $this->hasMany('Books', "ref", "book_id");
        }
    
    }
    
    
    class Books extends \Eloquent {
    
        protected $guarded = ['id'];
    
        public $timestamps = false;
    
        public function author()
        {
            return $this->hasOne('Authors');
        }
    
        public function categories(){
            return $this->hasMany('Categories');
        }
    
    }
    

    【讨论】:

    • 传说中的谢谢,我想我是在糊里糊涂,非常感谢。
    猜你喜欢
    • 2013-10-05
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2018-08-05
    • 2022-08-17
    • 1970-01-01
    • 2013-12-14
    相关资源
    最近更新 更多