【问题标题】:Laravel eloquent get all from one table and one from anotherLaravel 雄辩的从一张桌子和另一张桌子上得到所有
【发布时间】:2015-11-20 21:23:21
【问题描述】:

我正在使用$articles = Article::all(); 获取一个索引页面(使用带有$articles as $article 的foreach)我在一个表格中的所有文章。现在我想将此结果与另一个名为“设备”的表连接起来,并且只想在 $articles 中的结果中添加一个名为“名称”的列。 设备的“id”如果等于我的文章表中的“device_id”。 我可以做一个很大的选择

$articles = DB::table('articles')
        ->join('devices', 'articles.device_id', '=', 'devices.id')
        ->select('devices.name','articles.id','articles.text', ...)
        ->get();

但我不想这样做。有没有更好的选择来处理这个问题?

提前谢谢你,

量子论

【问题讨论】:

    标签: laravel select join eloquent


    【解决方案1】:

    你可以在模型中使用关系

    <?php
    namespace App\Models;
    use Illuminate\Database\Eloquent\Model as Eloquent;
    class Article extends Eloquent{
        public function device(){
             $this->belongsTo('App\Models\Device');
        }
    }
    
    <?php
        namespace App\Models;
        use Illuminate\Database\Eloquent\Model as Eloquent;
        class Device extends Eloquent{
            public function articles(){
                 $this->hasMany('App\Models\Article');
            }
        }
    

    当你得到$articles = Article::all();之后 您可以循环浏览文章

    foreach($articles as $article){
       echo $article->device->name
    }
    

    您也可以急切或延迟加载关系$articles = Article::with('device')-&gt;all();

    您还可以为特定设备获取所有文章

    Device::find(1)->articles()->get()
    

    【讨论】:

      猜你喜欢
      • 2011-10-09
      • 2020-07-29
      • 2019-02-25
      • 1970-01-01
      • 2017-08-28
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 2016-01-23
      相关资源
      最近更新 更多