I have table organisations
and another table clients
. An organisation can have many clients, and a client can belong to many organisations hence the many-to-many relationship and the pivot table client_organisation
.
In my model Organisation.php
I have the following,
class Organisation extends Eloquent {
//Organisation __has_many__ clients
public function clients()
{
return $this->hasMany('client');
}
}
and in my Client.php
model I have,
class Client extends Eloquent {
public function organisations()
{
return $this->belongsToMany('organisation');
}
}
The Pivot table migration,
<?php
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint;
class CreateClientOrganisationTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('client_organisation', function(Blueprint $table)
{
$table->increments('id');
$table->integer('client_id')->unsigned()->index();
$table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
$table->integer('organisation_id')->unsigned()->index();
$table->foreign('organisation_id')->references('id')->on('organisations')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('client_organisation');
}
}
I then run the following in my controller, to retrieve all the organisations and there clients,
$organisations = new Organisation;
$organisations->clients()->get();
however this results in the following error,
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'clients.organisation_id' in 'where clause' (SQL: select * from
clients
whereclients
.organisation_id
is null)
Now it is my understanding that should not need a clients.organisation_id
column in my database as I have a pivot table, what am I doing wrong? I want to be able to get all my organisations and their clients, using the pivot table.