Laravel雄辩地从一张桌子和另一张桌子中获得所有

时间:2015-11-20 21:23:21

标签: laravel select join eloquent

我正在使用$articles = Article::all();获取索引页面(使用带有$articles as $article的foreach)表格中的所有文章。现在我想将这个结果与另一个名为'devices'的表联系起来,并且只想在$ articles中为我的结果添加一个名为'name'的列。 设备的“id”等于我的articles-table中的“device_id”。 我可以用

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

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

提前谢谢你,

quantatheist

1 个答案:

答案 0 :(得分:0)

您可以在模型中使用关系

<?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')->all();

您可以为特定设备拍摄更多的艺术品

Device::find(1)->articles()->get()
相关问题