J
J
javanub2016-11-24 13:32:33
Laravel
javanub, 2016-11-24 13:32:33

Relationships in laravel, where is the error? Why does not see the table to which I am making a connection?

News table

class NewsModel extends Model
{
    protected $primaryKey = 'id';
    protected $table = 'news';

    public function country()
    {
        return $this->hasOne(CountryModel::class);
    }
}

Country table
class CountryModel extends Model
{
    protected $primaryKey = 'id';
    protected $table = 'country';
    public $timestamps = false;

    public function news()
    {
        return $this->belongsTo(NewsModel::class);
    }
}

Controller
public function all()
    {
        $news = NewsModel::find(1);
        return view('welcome', [ 'news' => $news]);
    }

View
I'm trying to link the news table to the country table, but there is no connection.
{{ dd($news->country->country) }}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nimfus, 2016-11-24
@Nimfus

1. It is worth checking the presence of the corresponding keys in the tables https://laravel.com/docs/5.3/eloquent-relationship...
2. See what error the parameter pulling from country gives
3. Redefine the keys manually
4. Test as indicated by the author of the answer above

A
Andrey Novikov, 2016-11-24
@Novikofff

Try this
Or

{{ dd($news->load('country')) }}

B
Big_person, 2016-11-25
@Big_person

It would be more logical to
use {{ dd($news->country-> name ) }}
Or do you have a country field in the country table?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question