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条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大