通过laravel获取关系数据

时间:2018-01-05 21:00:09

标签: laravel laravel-5 laravel-eloquent

我有2个表客户端和maintenance_packages,我正在尝试列出所有客户端及其维护包,但不断收到以下错误。

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'maintenance_packages.client_id' in 'where clause' (SQL: select * from `maintenance_packages` where `maintenance_packages`.`client_id` = 2 and `maintenance_packages`.`client_id` is not null limit 1)

我猜它是我建立关系的方式吗?以下是我的数据库迁移,模型和控制器。

客户端数据库

public function up()
{
    Schema::create('clients', function(Blueprint $table) {
        $table->increments('id');
        $table->string('name', 55);
        $table->string('email', 100);
        $table->integer('maintenance_id')->unsigned();
    });
}

维护DB

  public function up()
{
    Schema::create('maintenance_packages', function(Blueprint $table) {
        $table->increments('id');
        $table->string('name', 55);
        $table->integer('hours');
        $table->decimal('price');
    });
}

客户端模型

namespace App;
use App\MaintenancePackage;

use Illuminate\Database\Eloquent\Model;

class Client extends Model 
{

    protected $table = 'clients';
    public $timestamps = false;

    public function maintenance()
    {
        return $this->hasOne(MaintenancePackage::class);
    }

}

维护模式

namespace App;
use App\Client;

use Illuminate\Database\Eloquent\Model;

class MaintenancePackage extends Model 
{

    protected $table = 'maintenance_packages';
    public $timestamps = false;

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

}

控制器

public function index()
  {
      $clients = Client::with('maintenance')->get();
      return view('clients.index', compact('clients', 'maintenance'));
  }

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

在您的客户端模型中替换

public function maintenance()
{
    return $this->hasOne(MaintenancePackage::class);
}

public function maintenance()
{
    return $this->BelongsTo(MaintenancePackage::class, 'maintenance_id');
}

现在在维护模型中替换

public function client()
{
    return $this->belongsTo(Client::class);
}

public function client()
{
    return $this->hasOne(Client::class, 'maintenance_id');
}