Search code examples
laraveleloquenteloquent-relationship

How to get data from Laravel relation


I have 2 models: publictxt and Pulicetxtrecive

publictxt model:

class Publictxt extends Model
{
    protected $fillable=['sender','reciver','description','useridseen'];

    public function Publictxtrecives()
    {
        return $this->hasMany(Pulicetxtrecive::class,'publictxt_id', 'id');
    }
}

Pulicetxtrecive model:

protected $fillable=['publictxt_id','user_id','seen'];

public function publictxts()
{
    return $this->belongsTo(Publictxt::class);
}

I want to get the values ​​from the Publictxt that are available in the Pulicetxtrecive. When a record is stored in the Publictxt, users are registered in the Pulicetxtrecive after viewing.

$pulictxtcount=Publictxt::where('reciver',Auth::user()->shift)->orwhere('reciver',1)->with('Publictxtrecives')->whereHas('Publictxtrecives',function($q){$q->where('seen', '=', 0);})->count();

this code doesn't work.


Solution

  • I solved this problem:

    $pulictxtcount = Publictxt::where(function($q){$q->where('reciver',Auth::user()->shift)->orwhere('reciver',1);})->whereDoesntHave('Publictxtrecives', function($q){$q->where('user_id', Auth::user()->id); })->count();