Tushar Kumbhar
Tushar Kumbhar

Reputation: 1

Laravel with where like condition in relationship

I have a WorkPackage model with below relationship.

public function work_items()
{
    return $this->hasMany(WorkItem::class);
}

And WorkPackage has 'title','project_id' columns and work_items has 'title','work_package_id' columns. Now I want to search user typed keyword is matching with title in both table.

Here is my tried function

public function getWorkPackageProposals($projectId, $title)
{

    $result['data'] = $this->workPackage->with(['work_items' => function ($query) {
        $query->where('title', 'LIKE', "%{$title}%");
    }])
        ->where('project_id', $projectId)
        ->where('title', 'LIKE', "%{$title}%")
        ->get();
    return $result;
}

but its not working. Please find the below code for I used to create object of WorkPackage.

public function __construct(WorkPackage $workPackage)
{
    $this->workPackage = $workPackage;
    $this->setModel(WorkPackage::class);
    $this->workItemRepository = app(WorkItemRepository::class);
}

Upvotes: 0

Views: 106

Answers (3)

Alireza Mortezaei
Alireza Mortezaei

Reputation: 493

I think your problem will be solved with join method:

$result = $this->workPackage
->join('work_items', 'work_packages.id', '=', 'work_items.package_id')
->where('work_items.title', 'LIKE', '%{$term}%')
->orWhere('work_packages.title', 'LIKE', '%{$term}%')
->get();

Upvotes: 0

Tushar Kumbhar
Tushar Kumbhar

Reputation: 1

Below code works for me. Thanks to everyone for help to get right answer.

   $result['data'] = $this->workPackage->with(['work_items' => function ($q) use ($title) {
        $q->where('title', 'LIKE', "%{$title}%");
    }])
        ->where('project_id', $projectId)
        ->where('title', 'LIKE', "%{$title}%")
        ->get();
    return $result;

Upvotes: 0

STA
STA

Reputation: 34678

whereHas() works to specify additional filters for the related model to check :

$result['data'] = $this->workPackage->whereHas('work_items', function ($query) use ($title) {
        $query->where('title', 'LIKE', "%{$title}%");
    })
    ->where('project_id', $projectId)
    ->where('title', 'LIKE', "%{$title}%")
    ->get();
return $result;

Upvotes: 1

Related Questions