【问题标题】:Laravel/Eloquent - Eager Load using other than Primary KeyLaravel/Eloquent - 使用主键以外的 Eager Load
【发布时间】:2013-06-05 13:20:18
【问题描述】:

Eager Loading 在 IN(...) 子句中使用父表中的主键,正如 Laravel 文档中明确说明的那样:

从书中选择 *

select * from authors where book_id in (1, 2, 3, 4, 5, ...)

是否可以不使用主键,而是使用 books 表中的另一个键?甚至是从数据透视表中检索到的键?

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    是的,我们可以在非主列上进行预加载。为此,您需要在模型中定义 db-data 关系:-

    像这样定义你的模型书和作者:-

    class Books extends Eloquent {
    
        public static $table = 'books';    
    
         public function bookauthors(){
             return $this->has_many('authors','book_id');
    
         }
    
    }
    
    
    class Authors extends Eloquent {
    
        public static $table = 'authors';
    
    
         public function books()
         {
              return  $this->belongs_to('books','book_id');
         }
    
    }
    

    现在您可以使用以下代码行以“book_id”键为作者急切加载书籍:-

    $books = Books::with(array('bookauthors'))->get();
    

    我希望这对您有所帮助...我还没有在我的本地或测试数据库上进行测试。但对帖子-标签关系使用了类似的急切加载。

    【讨论】:

      猜你喜欢
      • 2017-02-22
      • 1970-01-01
      • 2019-06-10
      • 2013-06-20
      • 2015-03-01
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      相关资源
      最近更新 更多