Pixel
Pixel

Reputation: 910

Eloquent: Relationships

I have a big problem with the relation between two tables.
I want to link Subscription to Orders like this :

$subs = Subscription::first()->order->id

But nothing work i tried everything.

Subscription table : enter image description here

Order table : enter image description here

I tried this model but it don't work :

namespace App;

use Illuminate\Database\Eloquent\Model;

class Subscription extends Model
{
    public $timestamps = false;

    public function order()
    {
        return $this->hasOne('App\Order');
    }
}

Order model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    public $timestamps = false;

    public function payouts()
    {
        return $this->hasMany('App\Payout');
    }

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

error :

ErrorException: Trying to get property of non-object in /var/www/vhosts/trafficshield.tools/httpdocs/app/Http/Controllers/CampaignController.php:58

Line 58 : $order_id = Subscription::where('id', '=', 'GjhQpVSdQPirGmEEkJ6pGw')->first()->order->id;

Thank's for your

Upvotes: 0

Views: 47

Answers (1)

Leonardo Cabr&#233;
Leonardo Cabr&#233;

Reputation: 1235

Because you are using a non autoincrement value as primary key you have to put this in your models:

public $incrementing = false;

Upvotes: 1

Related Questions