donglaogu3788 2015-11-03 08:08
浏览 42
已采纳

在Laravel 5.1中使用雄辩的内部联接

I have a doubt that I couldn't find an answer anywhere. I'm new to eloquent and to make the basic stuff it is excelent! Now I need to query data from different tables and I was wondering if I can do it with eloquent. I have two models:

class Worker extends Model {

protected $table = 'workers';
public $timestamps = true;

public function area()
{
    return $this->belongsTo('Area');
}

}

And this one

class Area extends Model {

protected $table = 'areas';
public $timestamps = true;

public function worker()
{
    return $this->hasMany('Worker');
}

}

So basically a worker belongs to an area and an area has many workers. Now I want to show in a table the name of the worker and the name of the area that he belongs to.

I can do it using the query builder but I wanted to know if I can do it with eloquent.

I saw a post in laracast with this code:

$workers = Worker::with('area')->get();

Now when I use that I get the following error:

Class 'Area' not found

I don't know why I get that error when the function 'area' exists in the Worker class and in the WorkerController I'm using

use App\Area;

What I want to be able to do is the following:

@foreach ($workers as $worker)
<td>{{ $worker->name }}</td>
<td>{{ $worker->lastname }}</td>
<td>{{ $worker->areas->name }}</td>
@endforeach

Like I said, I already I'm able to accompish this using laravel's query builder but I just want to know if I can make more use of the Eloquent :) Thank you for your time.

Just in case anyone asks here is my raw query:

$workers = DB::table('workers')
                     ->join('areas', 'areas.id', '=', 'workers.area_id')
                     ->select('workers.*', 'areas.name as area')
                     ->get();

That's the one I'm using and it works perfectly fine, thank you! :)

  • 写回答

2条回答 默认 最新

  • dqask02082 2015-11-03 08:29
    关注

    You are missing namespaces in your relations.

    public function area()
    {
        return $this->belongsTo('App\Area');
    }
    

    and

    public function worker()
    {
        return $this->hasMany('App\Worker');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计