0

I'm using Datatables for displaying data. It works good, but when I want to display data from related tables (models), they do not appear.

Model Keyword.php

public function website() {
    return $this->belongsToMany('App\Website');
}

Model Website.php

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

'websites' database table: id, siteName, siteUrl
'keywords' database table: id, website_id, kwName

Url that should display data: projects/'.$website->id.'/edit (example: projects/2/edit - (edit is a blade)) So, at this Url I want to show a datatable that display all kwName for certain website_id(in this example /2/).

Please, help me what should I use and how to do this.

1 Answer 1

1

Your Eloquent relationships are the wrong way around.

keywords has a reference to website via website_id, this is a belongsTo relationship.

website is referenced by many keywords, so this is a hasMany relationship.

Laravel 5.4 Eloquent Relationships

Sign up to request clarification or add additional context in comments.

4 Comments

just to comment: you can make them point to eachother no problem e.g. $farmer->hasmany('chicken') and $chicken->hasone('farmer')
No, that won't work. In a good database design there's always a hasOne/hasMany, and a belongsTo/belongsToMany relation. What you're saying is that a chicken hasOne farmer (farmer keeps record of that 1 chicken, while also keeping record of 'many' other chickens via chicken.farmer_id).
yeah about that you are right, that was a typo. correction: it should be $chicken->belongsto('farmer'). good spot!
A website may have many keywords (website->hasMany('App\Keyword') A keyword (identical) can be found in many websites(keywords->belongsToMany('App\Website'). So, I think it is possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.