laravel eloquent one to one relationship code example
Example 1: whereHas site:https://laravel.com/docs/
use Illuminate\Database\Eloquent\Builder;
$posts = Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'code%');
})->get();
$posts = Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'code%');
}, '>=', 10)->get();
Example 2: laravel eloquent relationships
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
public function deployments()
{
return $this->hasManyThrough(Deployment::class, Environment::class);
}
}
Example 3: add data to laravel many to many relationship
1. $user->roles()->attach($roleId);
2. you may also pass an array of additional data to be inserted
$user->roles()->attach($roleId, ['expires' => $expires]);
3.
$user->roles()->detach($roleId);
4.
$user->roles()->detach();
5. Any IDs that are not in the given array will be removed from the intermediate
table
$user->roles()->sync([1, 2, 3]);
6. If you need to update an existing row in your pivot table, you may use
updateExistingPivot method. This method accepts the pivot record foreign
key and an array of attributes to update:
$user->roles()->updateExistingPivot($roleId, $attributes);