Laravel morph relationship - php

I have a question regarding saving polymorphic relationships in Laravel. This is the model i would like to create in laravel.
A shop has many products, and a product can be either an "item" an "event" or a "service".
I have the following tables:
shops
id
user_id
name
events
id
public
title
description
products
id
shop_id
productable_id
productable_type
This is how i set up the models:
class Shop extends Model{
public function products(){
return $this->hasMany('App\Product');
}
}
class Product extends Model{
public function productable(){
return $this->morphTo();
}
}
class Event extends Model{
public function product(){
return $this->morphOne('App\Product','productable');
}
}
I want to be able to do the following:
$shop = Shop::first()
$event = Event::create(['title'=>'Some event']);
$service = Service::create(['title' => 'Some service']);
$shop->products()->save($event);
$shop->products()->save($service);
But it doesn't work! When i try to save the relation i get:
Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1 no such column: shop_id (SQL: update "accendo_events" set "updated_at" = 2016-11-26 10:11:02, "shop_id" = 1 where "id" = 1)'
Anyone have an idea of where this is going wrong? I probably misunderstood something about this type of relationship...

First of all add a back relation to Shop from Product Model
class Shop extends Model
{
public function products()
{
return $this->hasMany('App\Product');
}
}
class Product extends Model
{
public function shop()
{
return $this->belongsTo('App\Shop');
}
public function productable()
{
return $this->morphTo();
}
}
class Event extends Model
{
public function product()
{
return $this->morphOne('App\Product', 'productable');
}
}
Now, I am not sure why you are trying to make an empty event and add it to all the products, but still if you want to do it for whatever use cases... please follow the below approach... :)
$shop = Shop::first(); //or $shop = Shop::find(1);
foreach($shop->products as $product) {
$event = Event::create([]);
$service = Service::create([]);
$product->productable()->saveMany([
$event, $service
]);
}
Let me know in the comments below if something doesn't work :)
-- Edit
First of all, please understand that you can not add an entry to productable_id or productable_type from a hasMany() relation. You need to make sure you are using a morph relation for such purposes.
Secondly, since you are trying to add products first and not events first, the insertion method is not working out for you. Please note that you must try to create an Event or Service first and then try to associate with a shop.
The simplest approach to doing it would be
$shop = Shop::first();
$event = Event::create(['title' => 'Some Event']);
$event->product()->create(['shop_id' => $shop->id]);
$service = Service::create(['title' => 'Some Service']);
$service->product()->create(['shop_id' => $shop->id]);
You can also, try to follow my first approach, but the one I just mentioned is definitely supposed to work... and actually that is how it is meant to be inserted/created.

Related

Laravel hasOne relation with where clause

I have a model called RealEstate, this model has a relation with another model called TokenPrice, I needed to access the oldest records of token_prices table using by a simple hasOne relation, So I did it and now my relation method is like following:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
class RealEstate extends Model
{
public function firstTokenPrice(): HasOne
{
return $this->hasOne(TokenPrice::class)->oldestOfMany();
}
}
By far it's fine and no complexity. But now, I need to involve another relation into firstTokenPrice.
Let me explain a bit more:
As my project grown, the more complexity was added it, like changing firstTokenPrice using by a third table called opening_prices, so I added a new relation to RealEstate called lastOpeningPrice:
public function lastOpeningPrice(): HasOne
{
return $this->hasOne(OpeningPrice::class)->latestOfMany();
}
So the deal with simplicity of firstTokenPrice relation is now off the table, I want to do something like following every time a RealEstate object calls for its firstTokenPrice:
Check for lastOpeningPrice, if it was exists, then firstTokenPrice must returns a different record of token_price table, otherwise the firstTokenPrice must returns oldestOfMany of TokenPrice model.
I did something like following but it's not working:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
class RealEstate extends Model
{
public function lastOpeningPrice(): HasOne
{
return $this->hasOne(OpeningPrice::class)->latestOfMany();
}
public function firstTokenPrice(): HasOne
{
$lop = $this->lastOpeningPrice;
if ($lop) {
TokenPriceHelper::getOrCreateFirstToken($this, $lop->amount); // this is just a helper function that inserts a new token price into `token_prices` table, if there was none exists already with selected amount
return $this->hasOne(TokenPrice::class)->where('amount', $lop->amount)->oldestOfMany();
}
return $this->hasOne(TokenPrice::class)->oldestOfMany();
}
}
I have checked the $this->hasOne(TokenPrice::class)->where('amount', $lop->amount)->oldestOfMany() using by ->toSql() method and it returns something unusual.
I need to return a HasOne object inside of firstTokenPrice method.
You can use ofMany builder for that purpose:
public function firstTokenPrice(): HasOne
{
$lop = $this->lastOpeningPrice;
if ($lop) {
TokenPriceHelper::getOrCreateFirstToken($this, $lop->amount); // this is just a helper function that inserts a new token price into `token_prices` table, if there was none exists already with selected amount
return $this->hasOne(TokenPrice::class)->ofMany([
'id' => 'min',
], function ($query) use ($lop) {
$query->where('amount', $lop->amount);
});
}
return $this->hasOne(TokenPrice::class)->oldestOfMany();
}
I used ->oldest() with a custom scope called amounted in TokenPrice model:
class TokenPrice extends Model
{
public function scopeAmounted(Builder $query, OpeningPrice $openingPrice): Builder
{
return $query->where('amount', $openingPrice->amount);
}
/....
}
And then changed my firstTokenPrice
public function firstTokenPrice(): HasOne
{
$lop = $this->lastOpeningPrice;
if ($lop) {
TokenPriceHelper::getOrCreateFirstToken($this, $lop->amount);
return $this->hasOne(TokenPrice::class)->amounted($lop)->oldest();
}
return $this->hasOne(TokenPrice::class)->oldestOfMany();
}
It's working, but I don't know if it's the best answer or not

Laravel Eloquent Model inheritance

I'm a new bit who is trying to build an app using Laravel 5.5, and the Eloquent model.
I have two classes: (1)
Customer
and (2)
VIPCustomer which extends Customer.
You may immediately tell VIPCustomer contains all attributes that a customer has, and other extra attributes.
Just to be clear, a customer may not be a VIP, and a VIP must be a customer; The customer may immediately opt-in to be a VIP the first time he shops.
Therefore, I am attempting to do something like this in the database:
Customer:
+------------------------+
|id|name|gender|join_date|
+------------------------+
VIPCustomer:
+----------------------------------+
|customer_id|valid_until|type|point|
+----------------------------------+
(customer_id is a foriegn key referencing Customer.id)
And accordingly, in the model php file:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
}
.
namespace App;
use Illuminate\Database\Eloquent\Model;
class VIPCustomer extends Customer
{
public $incrementing = false;
}
And that's it? I saw there are others saying I should using polymorphic relationship but I don't understand what it means.
In addition, is it possible to do instantiate a new VIP Customer something like this?
$customer = new VIPCustomer;
$customer->name = 'Alice';
$customer->gender = 'F';
$customer->type = 'gold';
$customer->point = 0;
$customer->save();
On top of that, say when the VIP membership ends, is it possible to preserve that person as Customer? Because I'm afraid deleting that person will delete him from both Customer and VIPCustomer tables.
Thank you very much in advance.
Your current VIPCustomer class looks like a class that holds a VIP data, not a subject (a customer). Then so, I would rename it as VIPCustomerData here and make a new VIPCustomer to inherit Customer class instead.
class Customer extends Model
{
protected $table = 'customers';
}
Make sure you define the table name to avoid it being guessed by inheritance. Then tell VIPCustomer to has a relation to VIPCustomerData.
class VIPCustomer extends Customer
{
public function vipData()
{
return $this->hasOne(VIPCustomerData::class, 'customer_id', 'id');
}
}
Now, the problem is whenever you're going to retrieve VIP customers like VIPCustomer::get(), you'll get whole customers instead. So, applying global scope is needed.
class VIPCustomer extends Customer
{
protected static function boot()
{
parent::boot();
static::addGlobalScope('weareviptypeofcustomer', function ($q) {
$q->has('vipData'); // only customers with vip data
});
}
public function vipData()
{
return $this->hasOne(VIPCustomerData::class, 'customer_id', 'id');
}
}
To create a new Customer as VIP, of course 2 queries is needed to insert here. Example,
$vipCustomer = new VIPCustomer;
$vipCustomer->name = 'Alice';
$vipCustomer->gender = 'F';
$vipCustomer->save();
$vipCustomerData = new VIPCustomerData;
$vipCustomerData->type = 'gold';
$vipCustomerData->point = 0;
$vipCustomer->vipData()->save($vipCustomerData);
Example of updating point.
$vipCustomerData = $vipCustomer->vipData; // or $vipCustomer->vipData()->first();
$vipCustomerData->point = 10;
$vipCustomerData->save();
Example of removing VIP status from customer. Of course just delete VIPCustomerData from its table.
$vipCustomer->vipData()->delete();
However, it's better to maintain these subjects as one class if there is no special column to treat each subject differently.
class Customer extends Model
{
protected $table = 'customers';
protected $with = ['vipData']; // always eager load related 'vipData'
protected $appends = ['is_vip']; // append 'is_vip' accessor
public function vipData()
{
return $this->hasOne(static::class, 'customer_id', 'id');
}
public function getIsVipAttribute()
{
return (bool) $this->vipData;
}
}
$customers = Customer::all();
foreach($customers as $customer) {
if ($customer->is_vip) {
// is VIP
} else {
}
}

one to many relationship in laravel

In my database, i have two tables notification and alertFrequency. The notification has field id and website_url and the alert frequency has id and notification_id. Both tables has models which is one to many. The notification can have one or many alertFrequency.
class Notification extends Model {
public function alertFrequencies() {
return $this - > belongsToMany('AlertFrequency::class');
}
}
namespace App;
use Illuminate\ Database\ Eloquent\ Model;
class AlertFrequency extends Model {
protected $table = 'alertFrequencies';
public function notification() {
return $this - > belongsTo(Notification::class);
}
}
in the notification model, i wrote a function called alert, that will give me the laastest alert associated with a specific websie.
public function alert(){
$alert_frequency = AlertFrequency::find('notification_id')->first();
$o_notification = $this->alertFrequencies()->where('notification_id',$alert_frequency->id)
->select('created_at')->orderBy('created_at')->first();
if($alert_frequency ==null){
return false;
}
return created_at;
}
Is this a right way to extract the data? i would appreciate any suggestions and helps?
Notification hasMany AlertFrequency
public function alertFrequencies(){
return $this->hasMany('App\AlertFrequency');
}
and,
$alert_frequency = AlertFrequency::with('notification')->orderBy('created_at','desc')->first();
loads the latest AlertFrequency along with it's notification.
See One to Many relationship and Eager loading in documentation.
to get laastest alert associated with a specific websie with url $website_url.
Notification::where('website_url', $website_url)->orderBy('created_at')->first();
hasMany relation :
public function alertFrequencies(){
return $this->hasMany('App\AlertFrequency','notification_id');
}

Accessors (Getter) & Mutators (Setter) On a Pivot Table in Laravel

I have a pivot table that connects users to workspaces. On the pivot table, I also have a column for role, which defines the users role for that workspace. Can I provide Accessor (Getter) & Mutator (Setter) methods on the role inside the pivot table? I have been trying to look all over, but details on pivot tables in eloquent are pretty sparse.
I am not sure if I have to setup a custom pivot model? If I do, an example would be awesome as the documentation on pivot models is very basic.
Thanks.
If all you need to do is access additional fields on the pivot table, you just need to use the withPivot() method on the relationship definition:
class User extends Model {
public function workspaces() {
return $this->belongsToMany('App\Models\Workspace')->withPivot('role');
}
}
class Workspace extends Model {
public function users() {
return $this->belongsToMany('App\Models\User')->withPivot('role');
}
}
Now your role field will be available on the pivot table:
$user = User::first();
// get data
foreach($user->workspaces as $workspace) {
var_dump($workspace->pivot->role);
}
// set data
$workspaceId = $user->workspaces->first()->id;
$user->workspaces()->updateExistingPivot($workspaceId, ['role' => 'new role value']);
If you really need to create accessors/mutators for your pivot table, you will need to create a custom pivot table class. I have not done this before, so I don't know if this will actually work, but it looks like you would do this:
Create a new pivot class that contains your accessors/mutators. This class should extend the default Pivot class. This new class is the class that is going to get instantiated when User or Workspace creates a Pivot model instance.
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class UserWorkspacePivot extends Pivot {
getRoleAttribute() {
...
}
setRoleAttribute() {
...
}
}
Now, update your User and Workspace models to create this new pivot table class, instead of the default one. This is done by overriding the newPivot() method provided by the Model class. You want to override this method so that you create an instance of your new UserWorkspacePivot class, instead of the default Pivot class.
class User extends Model {
// normal many-to-many relationship to workspaces
public function workspaces() {
// don't forget to add in additional fields using withPivot()
return $this->belongsToMany('App\Models\Workspace')->withPivot('role');
}
// method override to instantiate custom pivot class
public function newPivot(Model $parent, array $attributes, $table, $exists) {
return new UserWorkspacePivot($parent, $attributes, $table, $exists);
}
}
class Workspace extends Model {
// normal many-to-many relationship to users
public function users() {
// don't forget to add in additional fields using withPivot()
return $this->belongsToMany('App\Models\User')->withPivot('role');
}
// method override to instantiate custom pivot class
public function newPivot(Model $parent, array $attributes, $table, $exists) {
return new UserWorkspacePivot($parent, $attributes, $table, $exists);
}
}
I figured out how to use Accessors and Mutators on the Pivot table (I'm using Laravel 5.8)
You must use using() on your belongsToMany relationships, for example:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
public function workspaces() {
return $this->belongsToMany('App\Workspace')->using('App\UserWorkspace');
}
}
namespace App;
use Illuminate\Database\Eloquent\Model;
class Workspace extends Model {
public function users() {
return $this->belongsToMany('App\User')->using('App\UserWorkspace');
}
}
So, use your Pivot model:
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class UserWorkspace extends Pivot {
public function getRoleAttribute() {
// your code to getter here
}
public function setRoleAttribute($value) {
// your code to setter here
}
}
This is a difficult question. The solutions I can think of are smelly and may cause some problems later on.
I am going to extend on Patricus's answer to make it work.
I was going to comment on Patricus's answer but there is simply too much to explain. To make his solution work with attach and sync we must do some ugly things.
The Problem
First let's identify the problem with his solution. His getters and setters do work but the belongsToMany relationship doesn't use the Pivot model when running sync, attach, or detach. This means every time we call one of these with the $attributes parameter the non-mutated data will be put into the database column.
// This will skip the mutator on our extended Pivot class
$user->workspaces()->attach($workspace, ['role' => 'new role value']);
We could just try to remember that every time we call one of these we can't use the second parameter to attach the mutated data and just call updateExistingPivot with the data that must be mutated. So an attach would be what Patricus stated:
$user->workspaces()->attach($workspace);
$user->workspaces()->updateExistingPivot($workspaceId, ['role' => 'new role value']);
and we could never use the correct way of passing the pivot attributes as the attach methods second parameter shown in the first example. This will result in more database statements and code rot because you must always remember not to do the normal way. You could run into serious problems later on if you assume every developer, or even yourself, will just know not to use the attach method with the second parameter as it was intended.
The Solution (untested and imperfect)
To be able to call attach with the mutator on the pivot columns you must do some crazy extending. I haven't tested this but it may get you on the right path if you feel like giving it a try. We must first create our own relationship class that extends BelongsToMany and implements our custom attach method:
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class UserWorkspaceBelongsToMany extends BelongsToMany {
public function attach($id, array $attributes = [], $touch = true)
{
$role = $attributes['role'];
unset($attributes['role']);
parent::attach($id, $attributes, $touch);
$this->updateExistingPivot($id, ['role' => $role], $touch);
}
// You will need sync here too
}
Now we have to make each Model::belongsToMany use our new UserWorkspaceBelongsToMany class instead of the normal BelongsToMany. We do this by mocking the belongsToMany in our User and Workspace class:
// put this in the User and Workspace Class
public function userWorkspaceBelongsToMany($related, $table = null, $foreignKey = null, $otherKey = null, $relation = null)
{
if (is_null($relation)) {
$relation = $this->getBelongsToManyCaller();
}
$foreignKey = $foreignKey ?: $this->getForeignKey();
$instance = new $related;
$otherKey = $otherKey ?: $instance->getForeignKey();
if (is_null($table)) {
$table = $this->joiningTable($related);
}
$query = $instance->newQuery();
return new UserWorkspaceBelongsToMany($query, $this, $table, $foreignKey, $otherKey, $relation);
}
As you can see, we are still calling the database more but we don't have to worry about someone calling attach with the pivot attributes and them not getting mutated.
Now use that inside your models instead of the normal belongsToMany:
class User extends Model {
public function workspaces() {
return $this->userWorkspaceBelongsToMany('App\Models\Workspace')->withPivot('role');
}
}
class Workspace extends Model {
public function users() {
return $this->userWorkspaceBelongsToMany('App\Models\User')->withPivot('role');
}
}
Its impossible to use setters, will not affect pivot table... make the change in the controller instead.

Relationship method must return an object of type Relation (LogicException) Laravel 4.1

I have used Laravel 4 fair bit and it's the first time I've came across this problem.
My pager table:
class pager extends Eloquent
{
protected $table = 'pagers';
public function user()
{
return $this->belongsTo('User', 'bid');
}
public function pager_items()
{
return $this->hasMany('pager_item', 'pid');
}
}
As you can see the pager has many pager items, below is the pager item model which belongs to pager.
class pager_item extends Eloquent
{
protected $table = 'pager_items';
public function pager()
{
return $this->belongsTo('pager', 'pid');
}
}
If I try to insert new model like so:
$test = new pager_item;
$test->description = 'test';
$test->bid =1;
$test->cid =1;
$test->pid =1;
$test->save();
I receive:
LogicException
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
I haven't been able to spot any issues that will cause such error, any help is appreciated, thank you.
in a "belongs to" relation you should try to pass the object to save instead of the id.
$pager = pager::find(10);
$test->pager()->associate($pager);
btw, try to name the classes Uppercase... like
class Pager extends Eloquent
...

Categories