Chud37
Chud37

Reputation: 5007

One to many relationship with Laravel

Okay, I must be missing something simple here.

I have the 'kjv' table, each row is a verse from the kjv bible:

CREATE TABLE `kjv` (
  `id` int(11) NOT NULL,
  `book` varchar(140) COLLATE utf8mb4_unicode_ci NOT NULL,
  `chapter` smallint(6) DEFAULT NULL,
  `verse` int(11) DEFAULT NULL,
  `contents` mediumtext COLLATE utf8mb4_unicode_ci
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

;

I also have a commentary table, each row has a commentary on a particular verse.

CREATE TABLE `commentary` (
  `id` int(11) NOT NULL,
  `kjv_id` int(11) NOT NULL,
  `note` mediumtext COLLATE utf8mb4_unicode_ci NOT NULL,
  `type` tinyint(4) NOT NULL COMMENT 'BOOL',
  `intro` tinyint(1) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Okay. So, as I understand it, the I can fetch the commantary this way in my KJVController:

$results =   KJV::where('book', '=', $this->book)
            ->where('chapter', '=', $this->chapter)
            ->leftJoin('commentary', 'kjv.id', '=', 'kjv_id')
            ->get();
dd($results);

Which is great, but I don't get multiple commentaries when I display the results.

So, as per this example I added this function in the KJV model:

class KJV extends Model
{
    protected $table = "kjv";
    function commentary() {
        return $this->hasMany(Commentary::class);
    }
}

And added use App\Commentary; in my KJVController. Now again, as per the example, I should be able to reference ->comments somewhere in the KJV::where query, and remove the leftJoin. But no matter what I do I get errors.

Upvotes: 0

Views: 56

Answers (1)

Sletheren
Sletheren

Reputation: 2478

You will be able to access them like this:

KJV::where('book', $this->book)->where('chapter', $this->chapter)->first()->commentary

You don't need get() and also a side note: you don't need to specify = inside where

PS: Make sure the commentaries have their kjv_id set to the KJV ID you want to retrieve.

PS 2: if you want to retrieve all the commentaries for multiple kjvs, you can as follow:

KJV::where('book', $this->book)->where('chapter', $this->chapter)->with('commentary')->get()

Upvotes: 2

Related Questions