There are two Models. One is TradeLicence and another is BusinessCategory.
I have already established relationship between them. In TradeLicence there is a foreign key category_id which local key is id of BusinessCategory.
Trade Licence Model
class TradeLicence extends Model
{
use SoftDeletes;
protected $fillable = ['slug', 'name', 'category_id'];
public function businessCategories()
{
return $this->belongsTo(BusinessCategory::class,'category_id','id');
}
}
trade_licences migration Table:
class CreateTradeLicencesTable extends Migration
{
public function up()
{
Schema::create('trade_licences', function (Blueprint $table) {
$table->id();
$table->string('slug')->unique();
$table->foreignId->('category_id');
$table->string->('name');
$table->timestamps();
});
}
}
Business Category Model:
class BusinessCategory extends Model
{
use SoftDeletes;
protected $fillable = ['slug', 'name', 'fees'];
}
business_categories migration table:
class CreateBusinessCategoriesTable extends Migration
{
public function up()
{
Schema::create('business_categories', function (Blueprint $table) {
$table->id();
$table->string('slug')->unique();
$table->string('name');
$table->double('fees');
$table->timestamps();
});
}
For adding a "Trade Licence", I need to select a "Business Category" and it stores the value
incategory_id column of trade_licencestable. I'm able to retrieve the name and fees value through the relationship inside TradeLicense model.
The problem is:
There is a another Model named DailyEarning. The show() method of DailyEarningController will display fees amount (fee of selected category, which was selected at the time of creating a new trade licence) and created_at and updated_at value of each Trade License.
My Question is:
How to get the values of fees, created_at and updated_at or which Query should I use to retrieve the values by using "Eloquent"?
Related
I am a new in Laravel and I am trying to get the value from third column id in pivot table
I have 3 tables and 4th table is pivot table, so my table structure is as follow
TABLE Product Structure
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->foreignId('category_id')->constrained();
$table->timestamps();
});
Table Attributes Structure
Schema::create('attributes', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Table Attribute Value Structure
Schema::create('attribute_values', function (Blueprint $table) {
$table->id();
$table->string('value');
$table->foreignId('attribute_id')->constrained();
$table->timestamps();
});
and I also make pivot table attribute_product
Schema::create('attribute_product', function (Blueprint $table) {
$table->foreignId('product_id')->constrained();
$table->foreignId('attribute_id')->constrained();
$table->foreignId('attribute_value_id')->constrained();
});
<<<<<<<<<<< MODELS OF TABLE >>>>>>>>>>>>>>>>>>>>>>
1.Table Product
class Product extends Model
{
use HasFactory;
public function attributes()
{
return $this->belongsToMany(Attribute::class)->using(AttributeProduct::class)->withPivot('attribute_value_id');
}
}
2.Table Attribute
class Attribute extends Model
{
use HasFactory;
public function products()
{
return $this->belongsToMany(Product::class)->using(AttributeProduct::class)->withPivot('attribute_value_id');
}
}
Table Attribute Value
class AttributeValue extends Model
{
use HasFactory;
protected $guarded = [];
public function attribute_product()
{
return $this->hasMany(AttributeProduct::class, 'attribute_value_id');
}
}
AND also I make a model of pivot table
use Illuminate\Database\Eloquent\Relations\Pivot;
class AttributeProduct extends Pivot
{
use HasFactory;
public function value()
{
return $this->belongsTo(AttributeValue::class,'attribute_value_id');
}
}
<<<<<<<<<<<<<< DATA IN TABLES >>>>>>>>>>>>>>>>>>>>>>>>
TABLE PRODUCT
ID TITLE category_id
6 Samsung S22 2
TABLE ATTRIBUTE
ID NAME
1 SIZE
2 COLOR
TABLE ATTRIBUTE VALUES
ID VALUE attribute_id
1 SM 1
2 M 1
3 RED 2
4 BLUE 2
Pivot Table values attribute_product
product_id attribute_id attribute_value_id
6 1 1
6 2 4
Now I am using these commands in controller to find the value
$p = Product::find(6);
foreach($p->attributes as $value){
echo $value->name." = ". $value->pivot->attribute_value_id->value."<br>";
}
when I try to get the value on base of attribute_value_id from pivot table its give me this error
ErrorException
Attempt to read property "value" on int
So how I can solve this problem.
Thanks
The pivot relation value should be a hasOne, not a belongsTo.
class AttributeProduct extends Pivot
{
use HasFactory;
public function value()
{
return $this->hasOne(AttributeValue::class, 'id', 'attribute_value_id');
}
}
So in your foreach, you can now do:
foreach($p->attributes as $attribute){
echo $attribute->name." = ". $attribute->pivot->value->value."<br>";
}
Also try to keep your variable names straight. Don't write $p->attributes as $value if $value is clearly an $attribute.
I need to connect two tables in DB with relation one to one. Where 'id' from first table need to be the 'id' in the second table.
Table 1:
public function up()
{
Schema::disableForeignKeyConstraints();
Schema::create('devices', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('device_type', 20)->nullable();
$table->date('purchase_date')->nullable();
$table->date('activation_date')->nullable();
$table->date('deactivation_date')->nullable();
$table->bigInteger('companyId')->unsigned();
$table->timestamps();
$table->foreign('companyId')->references('id')->on('companies');
});
Schema::enableForeignKeyConstraints();
}
Table 2:
public function up()
{
Schema::disableForeignKeyConstraints();
Schema::create('device_news', function (Blueprint $table) {
$table->integer('x', 10)->nullable();
$table->integer('y', 10)->nullable();
$table->time('time')->nullable();
$table->bigIncrements('deviceId');
$table->timestamps();
$table->foreign('deviceId')->references('id')->on('devices');
});
Schema::enableForeignKeyConstraints();
}
I never had situation like this. Is it correct or I have to change something?
To create an Eloquent model for a legacy table that has no primary key, simply add the following to your model:
/**
* primaryKey
*
* #var integer
* #access protected
*/
protected $primaryKey = null;
/**
* Indicates if the IDs are auto-incrementing.
*
* #var bool
*/
public $incrementing = false;
You should still have a $table->bigIncrements('id'); on the second table, so the table gets a PK - but you create the relation on an unsigned biginteger, which is not a primary key.
Laravel naming conventions also dictates that a relational column should be device_id and not deviceId (same goes for your primary table, it should be company_id and not companyId). Doing this will make your life much easier when you start defining your relations on your models.
Schema::create('device_news', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('device_id');
$table->integer('x', 10)->nullable();
$table->integer('y', 10)->nullable();
$table->time('time')->nullable();
$table->timestamps();
$table->foreign('device_id')->references('id')->on('devices');
});
I'm creating a foreign key relationship between the orders and order_status tables. When I get a new order from the customer and ship that order, I set that order status to shipped when the order is received to that customer. I set shipped and received status, and then that order will start showing on the orders history page. Am I doing this correctly?
class CreateOrdersTable extends Migration
{
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('customer_name');
$table->string('customer_email');
$table->string('customer_contact');
$table->bigInteger('order_status_id')->unsigned();
$table->string('product_names');
$table->string('products_quantity');
$table->text('customer_address');
$table->timestamps();
});
}
Here's the order_status table:
class CreateOrderStatusTable extends Migration
{
public function up()
{
Schema::create('order_status', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('status')->nullable();
$table->timestamps();
});
}
}
From the looks of it, an Order could have multiple OrderStatuses. To facilitate this in Eloquent (not covered here), your order_status table needs another column referencing theorders table.
Add this to the order_status migration:
$table->bigInteger('order_id')->unsigned()->index();
$table->foreign('order_id')->references('id')->on('orders');
i have two table one is user which is parent and other is posts(child) table and its coulmns are
public function up(){
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('title');
$table->string('body');
$table->timestamps();
}
}
i have already specified
$this->hasOne('Post');
relation into user model. now i want to insert data into posts table where with form i can save data into title and body column into there respective id's.
If it's an authenticated user, you can do this:
auth()->user()->posts()->create($request->all());
To make create() method work you also need to have $fillable array with all properties in the Post model:
$protected fillable = ['title', 'body'];
I have 2 models and both they aren't using the ID from the table, but the field internal_id. So i customized my pivot schema but i got stuck on connecting them. Im getting the error:
General error: 1215 Cannot add foreign key constraint (SQL: alter table `seoshop_category_product` add constraint seoshop_category_product_category_id_foreign foreign key
(`category_id`) references `seoshop_categories` (`internal_id`) on delete cascade)
The code for the migration is:
Schema::create('seoshop_category_product', function(Blueprint $table)
{
$table->increments('id');
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('internal_id')->on('seoshop_categories')->onDelete('cascade');
$table->integer('product_id')->unsigned()->index();
$table->foreign('product_id')->references('internal_id')->on('seoshop_products')->onDelete('cascade');
$table->timestamps();
});
Both fields as seoshop_products.internal_id as seoshop_categories.internal_id are existing, column types are both int(11).
Can someone tell me what is going wrong?
Migrations for the tables seoshop_categories and seoshop_products
//seoshop_products
public function up()
{
Schema::create('seoshop_products', function(Blueprint $table)
{
$table->increments('id');
$table->integer('shop_id');
$table->integer('internal_id')->signed()->index();
$table->integer('internal_variant_id');
$table->string('visible');
$table->string('tags');
$table->timestamps();
});
}
//Table seoshop_categories
public function up()
{
Schema::create('seoshop_categories', function(Blueprint $table)
{
$table->increments('id');
$table->integer('internal_id')->signed()->index();
$table->datetime('seoshop_created_at');
$table->datetime('seoshop_updated_at');
$table->text('full_description');
$table->timestamps();
});
}
Okay so now i've create my table, and its working as how it should. I need to get my product with categories (many-2-many). So i use
SEOshopProduct::find(1)->with('categories')->get();
After a dd() the categories are empty and i've looked into my query how it is called:
[8] array(3) {
["query"] "select `seoshop_categories`.*, `seoshop_category_product`.`product_id` as `pivot_product_id`, `seoshop_category_product`.`category_id` as `pivot_category_id` from `seoshop_categories` inner join `seoshop_category_product` on `seoshop_categories`.`id` = `seoshop_category_product`.`category_id` where `seoshop_category_product`.`product_id` in (?)"
["bindings"] array(1) {
[0] 8
}
["time"] 0.37
}
The internal_id's of both products and categories is greater then 10.000 and i dont see it back in the query.
My models:
Product:
public function categories(){
return $this->belongsToMany('SEOshopCategory', 'seoshop_category_product', 'product_id', 'category_id');
}
Categories:
public function products(){
return $this->belongsToMany('SEOshopCategory', 'seoshop_category_product', 'category_id', 'product_id');
}
To setup the foreign key constraint, the field definitions need to match exactly. In this case, however, the seoshop_category_product.category_id field is defined as an UNSIGNED INT, but the referenced seoshop_categories.internal_id field is defined as a SIGNED INT. The same is true for the foreign key for your products.
So, you can either update the internal_id fields on your categories and products tables to be unsigned, or you can update your foreign key fields on your pivot table to be signed.
You can tell Laravel what the local and foreign keys are when you define the relationship in your model...
class Product extends Eloquent
{
public function categories() {
return $this->hasMany('Category', 'internal_id', 'id');
}
}
class Category extends Eloquent
{
public function products() {
return $this->hasMany('Product', 'internal_id', 'id');
}
}