【问题标题】:Laravel 5 one to many eloquent relationshipLaravel 5 一对多雄辩的关系
【发布时间】:2015-07-01 07:48:37
【问题描述】:

我有如下数据库表结构

users
  id
  name

articles
  id
  about_id
  author_id
  text

还有以下用户:

1 Alex
2 John

And 2 articles one written by (author_id) John(2) about (about_id)
Alex(1) and other written by (author_id) Alex(1) about (about_id)
John(2).

我的问题是名为“Article”的文章表的模型应该如何看待下面提到的关系。 我想访问文章对象以检索作者对象,例如:

$article = Article::find(1);
$article->author;

并检索文章所涉及的用户对象:

$article = Article::find(1);
$article->about;

我不得不提一下,我只有两个模型:文章和用户。

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    您的文章模型应如下所示

    class Article extends Model {
        public function author() {
            return $this->belongsTo("App\User", 'author_id');
        }
    
        public function about() {
            return $this->belongsTo("App\User", 'about_id');
        }
    }
    

    【讨论】:

    • 我只有 2 个模型:文章和用户,这意味着 about_id 列中的 id 也是用户(App\User),而不是不同的对象
    【解决方案2】:

    你也可以使用 hasMany

    class Article extends Model {
        public function author() {
            return $this->hasMany("App\Author", 'author_id', 'id');
        }
    
        public function about() {
            return $this->hasMany("App\About", 'author_id', 'id');
        }
    }
    

    【讨论】:

      【解决方案3】:
      use App\User;
      use App\Article;
      
      class Article extends Model {
      
          public function author() {
              return $this->belongsTo(Article::class, 'author_id');
          }
      
          public function about() {
              return $this->belongsTo(User::class, 'about_id');
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-08
        • 2015-04-28
        • 2018-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-14
        • 2019-03-10
        相关资源
        最近更新 更多