C
C
cryp242019-06-08 20:45:51
Laravel
cryp24, 2019-06-08 20:45:51

BelongsTo hasOne or how to get data from related table?

I’m stuck, I can’t get off the ground, please explain with my example:
There are two tables Districts (structure id, district) and Announcements (structure id, district_id, text)
Conditionally in the Announcements controller I write the following:

public function allads(){
        $adsall=Ads::orderBy('id','desc')->paginate(10);
        return view('test2', compact('adsall'));
    }

At the output in the view, I have an $adsall array with all ads, and using this construction, I display the data {{$ads->district_id}} . How to display not the district ID and its real name from the second table by checking the district_id field?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Ernest Faizullin, 2019-06-08
@cryp24

class District extends Model {
    public function ads () {
        $this->hasMany(Ad::class);
    }
}

class Ad extends Model {
    public function district () {
        $this->belongsTo(District ::class);
    }
}

$adsall = Ad::with(['district'])->latest()->paginate(10);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question