You need to learn this:
http://laravel.com/docs/5.1/eloquent-relationships#many-to-many
Just work through it and it should make sense. You need a pivot table for many to many.
Mick
Hi phpMick,
thank you for your answer.
Here is what I have:
app/User.php
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public function bonds()
{
return $this->belongsToMany(Bond::class);
}
}
app/Bond.php
class Bond extends Model
{
protected $fillable = ['description', 'amount', 'debtor_id', 'creditor_id'];
public function debtor()
{
return $this->belongsToMany(User::class, 'bond_user', 'debtor_id', 'user_id');
}
public function creditor()
{
return $this->belongsToMany(User::class, 'bond_user', 'creditor_id', 'user_id');
}
}
two new migrations:
public function up()
{
Schema::create('bonds', function (Blueprint $table) {
$table->increments('id');
$table->text('description');
$table->float('amount', 8, 2);
$table->integer('debtor_id');
$table->integer('creditor_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('bonds');
}
----------------------
public function up()
{
Schema::create('bond_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('debtor_id');
$table->integer('creditor_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('bond_user');
}
I can save a debtor_id and creditor_id if I create a bond. But if I try to get the User from $bond->debtor, I get an integer only.
I find the answer:
Bond model:
public function debtor()
{
return $this->belongsTo(User::class, 'debtor_id');
}
public function creditor()
{
return $this->belongsTo(User::class, 'creditor_id');
}
User model
public function bond_debtor()
{
return $this->hasMany(Bond::class, 'debtor_id');
}
public function bond_creditor()
{
return $this->hasMany(Bond::class, 'creditor_id');
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community